我想在我的測試中嘲笑一個調用,但我得到一個錯誤,因爲它調用真正的方法比嘲笑它。嘲笑不能模擬方法調用
這是我的方法
@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和設置代理時失敗。幫助我瞭解我在這裏做錯了什麼。
嘲笑的情況下,你能提供與頂級級別的註解完整的測試類的代碼? – developer
@javaguy你的意思是在我的主題類中自動裝配AwsService? – amulamul
您的測試期望awsService.getAllSecurityGroups()以yoyr模擬的ec2作爲參數來調用。但是你的代碼不會用你的模擬ec2來調用它。它通過調用configSetter()創建的ec2來調用它() –