【发布时间】:2017-03-29 17:43:15
【问题描述】:
我试图在我的测试中模拟一个调用,但我得到一个错误,因为它调用真实方法而不是模拟它。
这是我的方法
@Value("${omega.aws.nonprod-profile}")
private String nonProdProfile;
@Autowired
AwsService awsService;
public List<SecurityGroup> getAllSecurityGroups() {
AmazonEC2 ec2 = configSetter();
return awsService.getAllSecurityGroups(ec2);
}
protected AmazonEC2 configSetter() {
ProfileCredentialsProvider credentials = new ProfileCredentialsProvider(nonProdProfile);
ClientConfiguration clientCfg = new ClientConfiguration();
clientCfg.setProxyHost(this.proxyHost);
clientCfg.setProxyPort(Integer.valueOf(proxyPort));
clientCfg.setProtocol(Protocol.HTTPS);
return new AmazonEC2Client(credentials, clientCfg);
}
这是我的测试课
@InjectMocks
private AwsConfigurationLocal subject;
@Mock
private AwsService awsService;
@Test
public void TestgetAllSecurityGroups() throws Exception {
ec2 = Mockito.mock(AmazonEC2Client.class);
securityGroup = new SecurityGroup();
List<SecurityGroup> result = Collections.singletonList(securityGroup);
Mockito.when(awsService.getAllSecurityGroups(ec2)).thenReturn(result);
List<SecurityGroup> actual = subject.getAllSecurityGroups();
assertThat(actual, CoreMatchers.is(equals(result)));
}
测试实际上调用了受保护的方法 configSetter 并在设置代理时失败。帮助我了解我在这里做错了什么。
【问题讨论】:
-
能否提供带有顶级注释的完整测试类的代码?
-
@javaguy 你的意思是在我的主题类中自动装配 AwsService ?
-
您的测试期望 awsService.getAllSecurityGroups() 以 yoyr mocked ec2 作为参数调用。但是您的代码不会使用您的模拟 ec2 调用它。它使用调用 configSetter() 创建的 ec2 调用它
标签: java testing junit mockito