mockito 使用PowerMock模拟注入属性时出现空指针

omqzjyyz  于 2022-11-08  发布在  其他
关注(0)|答案(1)|浏览(611)

我正在使用PowerMock测试一个类,当要模拟的字段为空时,我会遇到空指针异常。我模拟了两个字段,一个指向Golf,另一个指向Tango。Golf模拟得很好,但NullPointer发生在Golf上。
PS:为了降低复杂度,我把代码浓缩了一下,它看起来可能不需要PowerMock,但在实际情况下它是需要的。
遵循我的代码:

@ApplicationScoped
public class Foo {

    @Inject
    private Tango tango;

    public int travel(Golf golf){

       Bar bar = new Bar();
       bar.setGolf(golf);

       return tango.fly(bar); // here tango is null, bar and golf are mocked
   }
}

@RunWith(PowerMockRunner.class)
@PrepareForTest({Foo.class, Tango.class})
public class FooTest{

    @Mock
    Golf golfMock;

    @Mock
    Tango tangoBar;

    @Test
    public void travelTest(){

       List<String> testList = Arrays.asList("a","b");
       Bar barMock = new Bar();
       barMock.setList(testList);

       PowerMockito.whenNew(Bar.class).withNoArguments().thenReturn(barMock);
       Foo fooMock = new Foo();
       Assert.assertTrue(fooMock.travel(golfMock) > 0);
    }
}
fbcarpbf

fbcarpbf1#

为了进一步说明另一个回复中提到的内容,这里有一个更明确的嘲讽方式,通常也不容易出错:

Foo foo = Mockito.mock(Foo.class); //initing a mock
when(foo.hello()).thenReturn("hello"); //mocking behavior
Bar bar = new Bar(foo); //dependency injecting the mock into a real class

相关问题