我想测试方法 deleteTracks ,为此,我需要模拟一个在调用playlistDaoBean.getPlaylistByUUID(uuid)
public class PlaylistBusines {
private PlaylistDao playlistDao;
@Inject
public PlaylistBusinessBean(PlaylistDaoBean playlistDaoBean){
this.playlistDaoBean = playlistDaoBean;
}
List<PlayListTrack> deleteTracks(String uuid, List<Integer> indexes) throws PlaylistException {
PlayList playList = playlistDaoBean.getPlaylistByUUID(uuid);
// TODO
}
这是我的课堂考试:
public class PlaylistBusinessTest {
@Inject
PlaylistBusinessBean playlistBusinessBean;
@Test
public void testRemoveTracks() throws Exception {
PlayList playList = new PlayList();
playList.setId(222)
playList.setName("fake name");
PlaylistDaoBean playlistDaoBeanMock = mock(PlaylistDaoBean.class);
when(playlistDaoBeanMock.getPlaylistByUUID(uuid)).thenReturn(playList);
playlistBusinessBean.removeTracks(uuid, Arrays.asList(2, 3));
}
答案 0 :(得分:1)
被测实例(PlaylistBusinessBean)由DI框架注入。但是,那是不使用测试中创建的PlaylistDaoBean的模拟。模拟只是局部变量,在任何地方都没有使用。
不是使用注入的PlaylistBusinessBean实例,而是以编程方式创建一个实例并将PlaylistDaoBean模拟传递给它:
public class PlaylistBusinessTest {
@Test
public void testRemoveTracks() throws Exception {
PlayList playList = new PlayList();
playList.setId(222)
playList.setName("fake name");
PlaylistDaoBean playlistDaoBeanMock = mock(PlaylistDaoBean.class);
when(playlistDaoBeanMock.getPlaylistByUUID(uuid)).thenReturn(playList);
PlaylistBusinessBean playlistBusinessBean = new PlaylistBusinessBean(playlistDaoBeanMock);
playlistBusinessBean.removeTracks(uuid, Arrays.asList(2, 3));
}
一般说明:
答案 1 :(得分:0)
之所以不起作用,是因为您没有将模拟作为参数提供给PlaylistBusines。
提供错误信息是值得的,但是您定义行为的模拟程序永远不会在被测类中使用。