繁体   English   中英

如何使用Mockito模拟服务?

[英]How to mock service with Mockito?

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

您正在嘲笑when(remoteService.getAll(anyString()))方法,并且正在调用getAll()

when(remoteService.getAll(anyString()))替换when(remoteService.getAll(anyString())) when(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;
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM