如何测试活动和服务之间的交互?
例如,我有一个管理当前音乐播放器播放队列的服务和一个向用户显示播放队列的活动。我想测试活动是否正确显示了播放队列。
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
不正确还是应该使用不同的测试类?