如何使用Mockito模拟注入对象的属性

时间:2018-12-14 14:36:01

标签: java mockito testng guice

我想测试方法 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));


    }

2 个答案:

答案 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));


    }

一般说明:

  • 这是一个单元测试,所以我总是建议独立于DI和任何注入的代码独立地测试代码。
  • 但是,如果确实需要,通常还可以使用特定于测试的DI上下文,该上下文在需要时将模拟注入到受测bean。该如何做取决于所使用的DI。

答案 1 :(得分:0)

之所以不起作用,是因为您没有将模拟作为参数提供给PlaylistBusines。

提供错误信息是值得的,但是您定义行为的模拟程序永远不会在被测类中使用。