我有一个Spring Shell应用程序。我需要测试命令。我的命令:

@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;
    }
}

关于java - 如何使用Mockito模拟服务?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50059638/

10-12 01:34