我有以下测试代码。我正在尝试测试是否从 SQLite 数据库填充列表。
public class ViewIssuesActivityTest extends BaseActivityTest<ViewIssuesActivity>{
private List<Issue> issues;
public ViewIssuesActivityTest() {
super(ViewIssuesActivity.class);
}
public void setUp() throws Exception {
super.setUp();
issues = new ArrayList<Issue>();
issues.add(new Issue("Trial","Desc","Location","ImagePath"));
IssueRepository issueRepository = mock(IssueRepository.class);
doAnswer(new Answer<Object>() {
@Override
public List<Issue> answer(InvocationOnMock invocation) throws Throwable {
return issues;
}
}).when(issueRepository).getIssues();
activity.setIssueRepository(issueRepository);
}
public void testNumberOfIssuesRecorded() {
ListView listView = (ListView) activity.findViewById(android.R.id.list);
assertEquals(1, listView.getCount());
}
}
我的 BaseActivityTest 代码是:
public class BaseActivityTest<T extends Activity> extends ActivityInstrumentationTestCase2<T> {
protected T activity;
public BaseActivityTest(Class<T> activityClass) {
super(activityClass);
}
@Override
protected void setUp() throws Exception {
activity = getActivity();
}
}
我的 ViewIssuesActivity 如下:
public class ViewIssuesActivity extends ListActivity{
private IssueRepository issueRepository;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(com.change.kranti.R.layout.issues);
issueRepository = new IssueRepository(getApplicationContext());
List<Issue> issues = new ArrayList<Issue>();
issues = issueRepository.getIssues();
ArrayAdapter<Issue> adapter = new ArrayAdapter<Issue>(this,
android.R.layout.simple_list_item_1, issues);
setListAdapter(adapter);
}
}
问题是我得到错误:expected<1> got <0>
我认为问题是在创建 issueRepository 之前调用了 onCreate 方法。我想模拟 IssueRepository 并测试我的列表是否被填充。
我的代码有什么问题,或者是否有更好的方法来测试此功能。
任何帮助将不胜感激。