如何测试活动与服务之间的互动?
例如,我有一个管理当前音乐播放器播放队列的服务和一个向用户显示播放队列的活动。我想测试活动是否正确显示播放队列。
public class ViewAvailableSongsActivityTests extends ActivityInstrumentationTestCase2<ViewAvailableSongsActivity> {
public ViewAvailableSongsActivityTests() {
super(ViewAvailableSongsActivity.class);
}
public void testOneAvailableSong() {
SongParcel song = new SongParcel("Test Title", "Test Artist", "content://testuri");
addSongToAvailableList(song);
Activity activity = this.getActivity();
ListView lstAvailableSongs = (ListView) activity.findViewById(R.id.lstAvailableSongs);
assertEquals(1, lstAvailableSongs.getCount());
assertListViewItemIsCorrect(lstAvailableSongs, 0, song);
stopMyService();
}
public void test3AvailableSongs() {
SongParcel songLast = new SongParcel("Test Title", "Test Artist1", "content://testuri");
addSongToAvailableList(songLast);
SongParcel songFirst = new SongParcel("A Good Song", "Test Artist2", "content://testuri");
addSongToAvailableList(songFirst);
SongParcel songMiddle = new SongParcel("Bravo", "David", "content://tests");
addSongToAvailableList(songMiddle);
Activity activity = this.getActivity();
ListView lstAvailableSongs = (ListView) activity.findViewById(R.id.lstAvailableSongs);
assertEquals(3, lstAvailableSongs.getCount());
assertListViewItemIsCorrect(lstAvailableSongs, 0, songFirst);
assertListViewItemIsCorrect(lstAvailableSongs, 1, songMiddle);
assertListViewItemIsCorrect(lstAvailableSongs, 2, songLast);
stopMyService();
}
private void addSongToAvailableList(SongParcel song) {
Context context = this.getInstrumentation().getTargetContext();
Intent addSongIntent = new Intent(context, MyService.class);
addSongIntent.setAction(MyService.ADD_SONG_TO_AVAILABLE_LIST);
addSongIntent.putExtra(MyService.EXTRA_SONG, song);
context.startService(addSongIntent);
}
private void assertListViewItemIsCorrect(ListView lstView, int index, SongParcel song) {
Adapter adapter = lstView.getAdapter();
View row = adapter.getView(0, null, lstView);
TextView txtTitle = (TextView) row.findViewById(R.id.txtTitle);
assertEquals(song.getTitle(), txtTitle.getText());
TextView txtArtist = (TextView) row.findViewById(R.id.txtArtist);
assertEquals(song.getArtist(), txtArtist.getText());
}
private void stopMyService() {
this.getActivity().stopService(new Intent(this.getInstrumentation().getTargetContext(), MyService.class));
}
}
我尝试使用ActivityInstrumentationTestCase2
,但我在使用该服务时遇到了问题。似乎该服务从测试持续到测试,因为该活动将始终显示3首歌曲。
我是否错误地使用ActivityInstrumentationTestCase2
或者我应该使用不同的测试类?
答案 0 :(得分:0)
事实证明我有一个错误,所以stopService()
永远不被称为= P.在assertListViewItemIsCorrect()
中,adapter.getView(0, null, lstView)
应该是adapter.getView(index, null, lstView)
。现在一切似乎都运转正常。