I want to write some unit tests, that use JUnit 4.12, Mockito 1.9.5 and PowerMock 1.6.1. The class has some fields annotated with @Mock, as well as some fields annotated with @InjectMocks. The attribute that is annotated with @InjectMocks reaches at some point a parent constructor which contains some static method invokation, that should be mocked with PowerMock. The problem is the first test works seamlessly, while the second test does not seem to mock the static methods at all.
@RunWith(PowerMockRunner.class)
@PrepareForTest({ StaticClass.class })
public class TestClass {
@Mock
private SomeClass attribute1;
@InjectMocks
private SomeOtherClass attribute2;
@BeforeClass
public static void setUp() {
PowerMockito.mockStatic(StaticClass.class);
when(StaticClass.staticMethod(any(), any()).thenReturn(new SomeConcreteClass());
}
@Test
public void test1() {
assertEquals(attribute2.method1(), value1);
}
@Test
public void test2() {
assertEquals(attribute2.method2(), value2);
}
}
public class SomeOtherClass {
private SomeClass attribute;
public SomeOtherClass() {
SomeConcreteClass value = StaticClass.staticMethod(argument1, argument2);
value.someOtherMethod();
}
}
As mentioned before, the first test passes and the StaticClass.staticMethod() is mocked as expected by PowerMock. The second test does not pass and it throws a NullPointerException at line when someOtherMethod is called on value (because value = null, as the StaticClass.staticMethod was not mocked anymore by PowerMock).
@Before
instead of@BeforeClass
? – secondwhen
expression on a non mocked objectattribute2
(your class under test). This is bound to fail. You might have made a typo and wanted to useattribute1
instead? – second