I have the following JUnit tests, and can't work out why the second test does not pass, the value of i
is 1 in both tests.
public class TestTest {
private AtomicInteger ai = new AtomicInteger(1);
@Test
public void test1() {
int i = ai.getAndIncrement();
Assert.assertEquals(1, i);
}
@Test
public void test2() {
int i = ai.getAndIncrement();
Assert.assertEquals(2, i);
}
}
test1
passes and test2
fails with the following message:
java.lang.AssertionError:
Expected :2
Actual :1
The tests are run on fresh instances. The behaviour of test1()
can't affect test2()
in any way, otherwise it could cause a single failing test to fail all other tests following it. That would make it harder to pinpoint the root of the problem, and you don't want that.
If you want to test behaviour between multiple calls, you'd need to either create a test that calls both those methods together as a single unit, or move on to integration testing where you can test larger amounts of code for correct working.
Your test is also logically wrong, since you're decrementing the value. Your (wrongly) expected value would be 0
instead of 2
.