![](/img/trans.png)
[英]Nullpointer in a @Mock (mocking final static Hashtable) with Powermock
[英]NullPointer when mock an inject attribute using PowerMock
我正在使用 PowerMock 測試一個類,當要模擬的字段為空時,我得到空指針異常。 我在嘲笑兩個領域,一個是高爾夫,另一個是探戈。 高爾夫被嘲笑得很好,但 NullPointer 恰好發生在高爾夫身上。
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);
}
}
為了擴展其他回復提到的內容,這里有一個更明確的,因此通常更不容易出錯的模擬方式:
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.