I'm new to JUnit5 and I noticed something weird happening.
Let's see it with an example,
I have a source class named A
class A {
someDownStreamService service;
void printer() {
int getData = service.getIntegerData();
print(getData);
}
}
Now when I wrote test case,
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
class JUnit5TestCaseForClassA {
@Mock
private someDownStreamService service;
@InjectMocks
private A a;
@BeforeEach
setUp() {
initMocks(this);
Mockito.when(service.getIntegerData()).thenReturn(25);
}
@Test
void test1() {
a.printer();
}
@Test
void test2() {
Mockito.when(service.getIntegerData()).thenReturn(19);
a.printer();
}
}
When I trigger test2() individually, the printer() function is printing 19 as I suppose Mockito.when() statement is overridden to return 19 in test2() function over what was registered in @BeforeEach to return 25.
And when I execute all the test classes under class 'JUnit5TestCaseForClassA', I see that printer() function is printing 25 for both these test function's. Is the overriding not happening? Or what is the issue?
Why is this discrepancy?????
I can see making @TestInstance(TestInstance.Lifecycle.METHOD), will resolve the issue, as each testcases are triggered with new test instance. But I want to test with Lifecycle.PER_CLASS.