如何使用Mockito模拟服务?

尼基塔·阿尔谢涅夫(Nikita Arseniev)

我有一个弹簧壳应用程序。我需要测试命令。我的命令:

@Autowired
private RemoteService remoteService;

@ShellMethod
public String list(){
    List<String> items= remoteService.getAll();
    return items.toString();
}

我的测试:

@Test
public void listCommandTest(){
    RemoteService remoteService=mock(RemoteService.class);
    when(remoteService.getAll()).thenReturn(new ArrayList<>());

    shell.evaluate(()->"list");

    verify(remoteConfigService).getAll();
}

我不需要调用RemoteService的真实方法getAll(),但是会调用它。如何解决?

特图尔卡

您如何将模拟服务注入被测代码中?

有两种选择:

1)通过构造函数注入模拟服务

@Autowired
public ShellCommands(RemoteService remoteService) {
    this.remoteService = remoteService;
}

2)创建测试配置

@Configuration
public class TestConfiguration {
    @Bean
    RemoteService remoteService() {
        RemoteService remoteService=mock(RemoteService.class);
        when(remoteService.getAll()).thenReturn(new ArrayList<>());
        return remoteService;
    }
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章