java - SPOCK:如何模拟供应商行为

标签 java unit-testing java-8 mockito spock

CompletableFuture 中执行 supplier 时,我试图涵盖积极的消极情况。出于某种原因,模拟值未在 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)
            }
        })

    }

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

时也会发生同样的情况

最佳答案

看来我对given 和when 的理解和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)
            }
        })

    }

关于java - SPOCK:如何模拟供应商行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55607623/

相关文章:

java - 使用 gradle 和 intellij 为 JavaFX 构建 FatJar,得到 NoClassDefFOundError

c# - 在您的单元测试项目中引用 System.Windows.Form 是一种不好的做法吗?

java - Stream使用过程中出现异常如何捕获和修改数据

java - 在可比数组上找不到符号

java - Android ListView 不刷新

java - 如何将 Android 应用程序上传到市场?

java - Grails 内置测试

node.js - 如何在 Jest 中测试来自 Express 的响应数据

java - Joda time : DateTimeComparator. Java 8 Time Api 有什么相似之处?

java - 使用 Java 8 Stream 读取文本文件 block