我正在测试一个带有void返回类型和一个参数的方法。我试图至少获得一些代码覆盖率。下面是我正在测试的一个方法:
@Service
public class VaultService {
private final ProductRepository repository;
private final DatabaseService databaseService;
public VaultService(
@Autowired BuildProperties buildProperties,
ProductRepository repository,
DatabaseService databaseService
) {
logger.info("Creating service");
this.repository = repository;
this.databaseService = databaseService;
}
protected void checkVaultResponseErrors(VaultResponse vaultResponse) {
if (vaultResponse.responseStatus != ResponseStatus.SUCCESS) {
vaultResponse.errors.forEach(error -> {
if (vaultResponse.responseStatus.equals(ResponseStatus.EXCEPTION)) {
throw new VaultException(error.getMessage());
}
if (vaultResponse.responseStatus.equals(ResponseStatus.FAILURE)) {
throw new VaultFailure(error.getMessage());
}
});
}
}
VaultResponse类如下所示
@Getter
@Setter
@JsonInclude(JsonInclude.Include.NON_NULL)
public class VaultResponse {
@JsonProperty("responseStatus")
public ResponseStatus responseStatus;
@JsonProperty("errors")
public List<Error> errors;
}
这是我的测试,我得到了一个Mockito.verify
的错误,但是其余的代码也没有得到任何覆盖,很明显我做错了什么。
@Test
void should_check_vaultResponse_for_errors() {
VaultService spyService = Mockito.spy(vaultService);
VaultResponse vaultResponse = new VaultResponse();
ResponseStatus status = ResponseStatus.SUCCESS;
List<Error> error = new ArrayList<>();
vaultResponse.setResponseStatus(status);
vaultResponse.setErrors(error);
doThrow(IllegalArgumentException.class)
.when(spyService).checkVaultResponseErrors(vaultResponse);
doNothing().when(spyService).checkVaultResponseErrors(vaultResponse);
verify(spyService, times(1)).checkVaultResponseErrors(vaultResponse);
}
1条答案
按热度按时间n7taea2i1#
您的测试方法清楚地表明您要测试
checkVaultResponseErrors
方法。这意味着您绝对不应该模拟它。您可以模拟使它工作所需的任何东西,但不能模拟方法本身。在我看来,需要编写三个测试:
1.无错误:
1.但有一个例外:
1.失败: