这是CustomAdapter(顺便说一句:真的很旧的代码,有一天应该改进):
public class CustomAdapter extends BaseAdapter{
private SortedSet<Integer> mHiddenItems = new TreeSet<>();
@Override
public final int getCount(){
return mHiddenItems.size();
}
...
}
这是我的测试类CustomAdapterTest(一切都运行良好):
public class CustomAdapterTest extends TestCase{
private static final int ITEMS_IN_ADAPTER = 10;
private CustomAdapter mCustomAdapter;
@Override
public void setUp() throws Exception{
super.setUp();
mCustomAdapter = EasyMock.createMockBuilder(CustomAdapter.class)
.addMockedMethod("method1")
.addMockedMethod("method2")
.createMock();
expect(mCustomAdapter.method2()).andReturn(ITEMS_IN_ADAPTER).anyTimes();
}
public void testOne(){
EasyMock.replay(mCustomAdapter);
assertEquals(ITEMS_IN_ADAPTER,mCustomAdapter.getTotalCount());
.....
}
......
}
尝试使用Robolectric,修复一个错误之后,这就是CustomAdapterTest的样子:
@RunWith(RoboelectricGradleTestRunner.class)
@Config(constants = BuildConfig.class , packageName="my.package.name")
public class CustomAdapterTest{
private static final int ITEMS_IN_ADAPTER = 10;
private CustomAdapter mCustomAdapter;
@Before
public void setUp(){
System.setProperty("dexmaker.dexcache",RuntimeEnvironment.application.getCacheDir().getPath())
mCustomAdapter = EasyMock.createMockBuilder(CustomAdapter.class)
.addMockedMethod("method1")
.addMockedMethod("method2")
.createMock();
expect(mCustomAdapter.method2()).andReturn(ITEMS_IN_ADAPTER).anyTimes();
}
public void testOne(){
EasyMock.replay(mCustomAdapter);
assertEquals(ITEMS_IN_ADAPTER,mCustomAdapter.getTotalCount());
.....
}
......
}
当我使用Robolectric运行CustomAdapterTest#testOne()时,我不知道为什么但是mCustomAdapter.mHiddenItems
为空,在调用mCustomAdapter.getCount()时导致NPE。 CustomAdapterTest的第一个版本没有发生这种情况。
1)为什么不使用RobolectricGradleTestRunner private SortedSet mHiddenItems = new TreeSet<>();
?
2)如何解决这个问题?我希望它按预期执行private SortedSet mHiddenItems = new TreeSet<>();
。
答案 0 :(得分:0)
这不是你问题的确切答案。但我只是在测试和测试课程。
我会删除部分模拟并在构造函数或setter中注入项目。或者我会在构造函数中再次模拟项目提供程序。