junit MonoJust -如何在单元测试中使用/ map()未被调用

bhmjp9jg  于 2022-11-11  发布在  其他
关注(0)|答案(1)|浏览(151)

有一个单元测试代码:

@Mock
    Client client;

    @Test
    public void test() {

        doAnswer(r -> {
            response.setData(data);
            return Mono.just(response);
        }).when(client).doSomething(any(Response.class));
        ...
        foo();
     }

在代码方法中,“doSomething”用法如下:

public void foo() {
        Response result = new Response();
        client.doSomething(result).map( resp -> {
            // THIS CODE IS NOT EXECUTED IN JUNIT TEST
            if (somelag) {
               ...
            }
            return resp;
        }
    }

问题:

如何在junit测试中以正确的方式执行这段代码?

备注

  • 在运行时它工作正常
  • 问题与线程有关(可能)
  • 在运行时有(reactor.core.publisher.Mono
public final <R> Mono<R> map(Function<? super T, ? extends R> mapper) {
    return this instanceof Fuseable ? onAssembly(new MonoMapFuseable(this, mapper)) : onAssembly(new MonoMap(this, mapper));
}
  • 在运行时:this instanceof Fuseable == false
  • 在junit中this instanceof Fuseable == true
  • 在方法(reactor.core.publisher.Monohook == nullHooks.GLOBAL_TRACE == false中的j单元测试中
protected static <T> Mono<T> onAssembly(Mono<T> source) {
        Function<Publisher, Publisher> hook = Hooks.onEachOperatorHook;
        if (hook != null) {
            source = (Mono)hook.apply(source);
        }

        if (Hooks.GLOBAL_TRACE) {
            FluxOnAssembly.AssemblySnapshot stacktrace = new FluxOnAssembly.AssemblySnapshot((String)null, (Supplier)Traces.callSiteSupplierFactory.get());
            source = (Mono)Hooks.addAssemblyInfo(source, stacktrace);
        }

        return source;
    }
dly7yett

dly7yett1#

您需要访问在foo()中使用的mono(此处为responseMono),并在其上调用.block(Duration...)方法

@Mock
Client client;

@Test
public void test() {

    doAnswer(r -> {
        response.setData(data);
        return Mono.just(response);
    }).when(client).doSomething(any(Response.class));
    ...
    responseMono = foo();

    responseMono.block(Duration.ofSeconds(1)); // <-- REQUIRED

    ...
    assertThat(...); // NOW IS OK
 }

foo()返回了我的示例中的responseMono

public Mono<Response> foo() {
    Response result = new Response();
    Mono<Response> responseMono = client.doSomething(result).map( resp -> {

        if (someFlag) {
           ...
        }
        return resp;
    }
    ...
    return responseMono;
}

相关问题