SPOCK:如何模拟供应商行为

时间:2019-04-10 08:05:09

标签: java unit-testing java-8 mockito spock

我正在尝试在supplier内执行CompletableFuture时掩盖肯定的否定情形。由于某些原因,模拟值未在supplier中传递。我的单元测试用例是使用spock框架编写的,由于我不太熟悉该框架,因此我不确定在进行模拟时是否犯错,或者供应商在进行模拟时缺少某些东西。

正在测试的代码:

CompletableFuture
    .supplyAsync(() -> s3Service.upload(bucket, key, file), executor)
    .handle(((putObjectResult, throwable) -> {
        if (throwable != null) {
            CustomRuntimeException exception = (CustomRuntimeException) throwable;
            log.error(exception);
        }
        return putObjectResult;
    }))
    .thenAccept(putObjectResult -> {
        if (putObjectResult != null) {
             FileUtils.deleteQuietly(file);
             log.debug("Deleted file {}", file.getName());
        }
    });

Spock测试代码:

@SpringBean
private S3Service s3service = Mock()

def "failed to upload article into s3"() {
    given: "mock the s3 service to throw CustomRuntimeException"
    s3Service.upload(_, _, _) >> {

        CompletableFuture<PutObjectResult> exception = new CompletableFuture<>();
        exception.completeExceptionally(new CustomRuntimeException())
        exception.exceptionally(new Function<Throwable, PutObjectResult>() {
            @Override
            PutObjectResult apply(Throwable throwable) {
                throw new CompletionException(throwable)
            }
        })

    }

现在,当我调试单元测试用例时,throwable中的.handle实例始终是null。当我嘲笑PutObjectResult

时也发生了同样的情况

1 个答案:

答案 0 :(得分:0)

所以看来我对给定的理解以及何时与Mockito框架的理解有所不同。 我已经将我的s3Service.upload(_, _, _)放在then部分中,并且文本情况按预期工作。所以最终的代码是:

@SpringBean
private S3Service s3service = Mock()

def "failed to upload article into s3"() {
    given: "mock the s3 service to throw CustomRuntimeException"
    // given conditions
    when: "check here the with the actual beans"
    // actual bean calls
    then: "mention your mocks and calls"
    1 * s3Service.upload(_, _, _) >> {

        CompletableFuture<PutObjectResult> exception = new CompletableFuture<>();
        exception.completeExceptionally(new CustomRuntimeException())
        exception.exceptionally(new Function<Throwable, PutObjectResult>() {
            @Override
            PutObjectResult apply(Throwable throwable) {
                throw new CompletionException(throwable)
            }
        })

    }