我试图在我的测试中模拟一个调用,但我得到了一个错误,因为它调用的是真正的方法,而不是模拟它。
这是我的方法
@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,并在设置代理时失败。请帮助我理解我在这里做错了什么。
发布于 2017-03-30 01:57:35
subject.getAllSecurityGroups();调用真正的configSetter(),它返回真正的AmazonEC2,然后传递给awsService.getAllSecurityGroups(ec2);。该参数与您的模拟ec2不匹配,因此默认的模拟实现将作为actual返回(我猜它是null)。
所以问题是:没有任何东西会阻止调用configSetter()的真正实现。如果您使用@Spy注释subject并执行
Mockito.when(subject.configSetter()).then(ec2);它应该像预期的那样工作。
也就是说,有很多设置只是为了检查被委托的简单调用。这是AwsConfigurationLocal中两个职责的适当混合--创建AmazonEC2Client和提供getAllSecurityGroups()。如果您将前者移到单独的类中(假设是AmazonEC2ClientFactor),那么一切都应该到位。
发布于 2017-03-30 14:23:41
尝试使用powerMockito返回AmazonEC2的模拟实例
@RunWith(PowerMockRunner.class)
@PrepareForTest({AwsConfigurationLocal.class})//assuming this is your test class
@InjectMocks
private AwsConfigurationLocal subject=PowerMockito.spy(AwsConfigurationLocal.class);//or try Mockito.spy instead, whichever works
@Test
public void TestgetAllSecurityGroups() throws Exception {
ec2 = Mockito.mock(AmazonEC2Client.class);
PowerMockito.doReturn(ec2).when(subject).configSetter().withNoArguments();
//your code
}https://stackoverflow.com/questions/43100552
复制相似问题