I’m trying to test a class A which in turn autowires a class B :
public class A {
@Autowired
private B b;
public int foo(int x, int y) {
int z = b.bar(x, y, false);
//do something with z
return z;
}
}
I’m using junit together with powermock and mockito to try to test the method foo in class A.
@RunWith(PowerMockRunner.class)
@PrepareForTest(A.class)
public class TestA {
@Test
private void testFoo() {
B b = PowerMockito.mock(B.class);
when(b.bar(2,3,false)).thenReturn(5);
A a = PowerMockito.spy(new A());
Whitebox.setInternalState(a, "b", b);
int z = a.foo(2,3);
Assert.assertEquals(10,z);
}
}
When i try to run the test I get a NullPointerException from within class B.
After using the debugger, I found out that right after stubbing the bar method of the B class, the bar method gets called.
The null pointer exception in this case is normal because the B class is not properly initialized.
Can anyone explain why this is happening and what can I do about it.
I’m not a PowerMockito user, but don’t you need to use
@PrepareForTest(B.class)? I think that annotation is for the class(es) you are mocking which is final or has statics, not for the class under test.Also, why are you using
spy()on A? Perhaps your example code doesn’t expose it, but I don’t see the use. And besides, do you really needPowerMockito.spy()for A, or would simply using Mockito’s spy() be sufficient (i.e., are both A & B final and/or have statics that you need to access/mock/verify)?Can I ask why you are using PowerMockito at all instead of just Mockito? If it was merely to set the private B inside of A with
Whitebox, you can do that with Mockito alone. You just declare your A and B outside of the test method as:and it will inject all @Mock mocks (i.e.,
b) into A.PowerMock is mostly useful for cases where you are mocking static methods or final classes/methods.