[英]Mocked object is null when using PowerMock/Mockito
我试图使用PowerMock和Mockito对我的一种方法进行单元测试,并为我已经在测试中模拟和定义行为的对象之一获取NUllPointerException。
这是我要测试的代码
protected void setTabList() {
List<ActionBar.Tab> list = TabAdapter.get().getAllEnabledTabs();
listAdapter.setTabList(list);
int itemCount = list.size();
if (itemCount == 1 && list.get(0).equals(TabAdapter.KEYPAD_TAB)) {
header.setVisibility(View.VISIBLE);
listAdapter.hide();
}
}
这是测试代码
@RunWith(PowerMockRunner.class)
@PrepareForTest({Log.class, TabFragment.class, TextView.class, SystemProperties.class})
public class TabFragmentTests extends TestCase {
@Before
public void setUp() {
suppress(method(Log.class, "println_native"));
suppress(everythingDeclaredIn(TextView.class));
suppress(method(SystemProperties.class, "native_get_boolean"));
suppress(method(SystemProperties.class, "native_get", String.class));
tabFragment = new TabFragment();
listAdapter = Mockito.mock(TabList.class);
}
@Test
public void testSetTabList() {
assertNotNull(tabFragment);
assertNotNull(listAdapter);
TabAdapter instance = TabAdapter.get();
TabAdapter spy = spy(instance);
List<ActionBar.Tab> list = new ArrayList<ActionBar.Tab>();
list.add(KEYPAD_TAB);
doAnswer(new Answer<String>() {
@Override
public String answer (InvocationOnMock invocation) {
return "set Tabs";
}
}).when(listAdapter).setTabList(list);
doAnswer(new Answer<String>() {
@Override
public String answer (InvocationOnMock invocation) {
return "hide";
}
}).when(listAdapter).hide();
doReturn(list).when(spy).getAllEnabledTabs();
tabFragment.setTabList();
verify(listAdapter, times(1)).hide();
}
当我运行测试和tabFragment.setTabList()
被调用时, listAdapter
在setTabList()
抛出NPE。 我试图理解为什么listAdapter.setTabList(list)
不能由测试中使用的“答案” API代替。
我也尝试过使用Mockito.doNothing().when(listAdapter).setTabList(list)
但这不能解决问题。
另一个观察结果是,当我在TabFragment类中创建一个虚拟的getTestString(listAdapter)
方法,并在我的测试中使用tabFragment.getTestString(listAdapter)
调用该方法时,将模拟的listAdapter作为参数传递,但它没有通过NPE。 这是否意味着我必须将模拟对象显式传递给方法调用?
您正在重写这样的方法调用:
when(listAdapter).setTabList(list);
但是您可以这样称呼它:
tabFragment.setTabList();
我不知道那将如何工作。 setTabList(列表); 和setTabList(); 调用不同的方法。
我认为您忘记将“ TabAdapter”类添加到“ PrepareForTest”批注中:
@PrepareForTest({Log.class, TabAdapter.class, TabFragment.class, TextView.class, SystemProperties.class})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.