java 空隙法的J单元检验

nxowjjhe  于 2023-02-02  发布在  Java
关注(0)|答案(1)|浏览(101)

我正在测试一个带有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);
}
n7taea2i

n7taea2i1#

您的测试方法清楚地表明您要测试checkVaultResponseErrors方法。这意味着您绝对不应该模拟它。您可以模拟使它工作所需的任何东西,但不能模拟方法本身。
在我看来,需要编写三个测试:
1.无错误:

// create VaultResponse without errors; you have that now

assertDoesNotThrow(() -> vaultService.checkVaultResponseErrors(vaultResponse));

1.但有一个例外:

// create VaultResponse with status EXCEPTION

VaultException thrown = assertThrows(VaultException.class,
        () -> vaultService.checkVaultResponseErrors(vaultResponse));
// you can now assert that thrown is what you expect

1.失败:

// create VaultResponse with status FAILURE

VaultFailure thrown = assertThrows(VaultFailure.class,
        () -> vaultService.checkVaultResponseErrors(vaultResponse));
// you can now assert that thrown is what you expect

相关问题