我有一个spring shell应用程序。我需要测试命令。我的命令:
@Test
public void listCommandTest(){
RemoteService remoteService=mock(RemoteService.class);
when(remoteService.getAll()).thenReturn(new ArrayList<>());
shell.evaluate(()->"list");
verify(remoteConfigService).getAll();
}
我的测试:
RouterModule.forRoot([
{ path: '', component: HomeComponent, pathMatch: 'full' },
{
path: '', component: RootComponent,
children: [
{ path: 'welcome', component: WelcomeComponent },
]
},
{ path: '**', redirectTo: '', pathMatch: 'full' },];
我不需要调用RemoteService的实际方法getAll(),但是它被调用。如何解决?
答案 0 :(得分:2)
您正在嘲笑when(remoteService.getAll(anyString()))
方法,而您正在调用getAll()
。
将when(remoteService.getAll(anyString()))
替换为when(remoteService.getAll())
答案 1 :(得分:1)
如何将模拟服务注入到测试代码中?
有两种选择:
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;
}
}