替换
我有一个弹簧壳应用程序。我需要测试命令。我的命令:
@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();
}
我不需要调用远程服务的真实方法getall((,但它被称为。如何修复它?
您正在模拟when(remoteService.getAll(anyString()))
方法,并且正在调用getAll()
。
when(remoteService.getAll())
when(remoteService.getAll(anyString()))
您如何将模拟服务注入正在测试的代码中?
有两个选项:
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;
}
}