如何使用Mockito模拟服务?

时间:2018-04-27 09:43:29

标签: java junit mockito

我有一个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(),但是它被调用。如何解决?

2 个答案:

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