I have the following test class:
@RunWith(PowerMockRunner.class)
@PrepareForTest(Foo.class)
public class MyTestClass {
@BeforeClass
public static void setUpBeforeClass() {
// class Foo: singleton pattern
Foo mockFoo = Mockito.mock(Foo.class);
when(mockFoo.theMethod()).thenReturn(...);
PowerMockito.mockStatic(Foo.class);
PowerMockito.when(Foo.getInstance()).thenReturn(mockFoo);
}
@Before
public void setUp() {
}
@After
public void tearDown() {
}
@AfterClass
public static void tearDownAfterClass() {
}
// MyClass.myStaticMethod() calls to some point Foo.getInstance().theMethod()
// when the MyTestClass in executed as JUnit in Eclipse this test passes
// when this test
@Test
public void test1() {
MyClass.myStaticMethod(myargs);
}
// when the MyTestClass in executed as JUnit in Eclipse this test fails because Foo.getInstance() returns null
// but this test passes if it is executed standalone (test2() selected and run as JUnit test in Eclipse)
@Test
public void test2() {
MyClass.myStaticMethod(myargs);
}
// when the MyTestClass in executed as JUnit in Eclipse this test fails because Foo.getInstance() returns null
// but this test passes if it is executed standalone (test3() selected and run as JUnit test in Eclipse)
@Test
public void test3() {
MyClass.myStaticMethod(myargs);
}
}
I know that setUpBeforeClass() is run only once before the first test, I know that the framework JUnit create a new instance of MyTestClass for each test run. But I am unable to understand why when I execute as JUnit the class only the first test passes while each test passes when I run they as JUnit in a standalone manner. Could you please tell me why? Why the mocking "survives" only for the first test executed? If the code in setUpBeforeClass() is not in setUpBeforeClass() but in setUp(), which is executed before each test, all tests pass when I execute the class as JUnit.