1

我在我的Quarks 应用程序中使用 Smallrye Mutiniy 反应库,因为它在 Quarks 应用程序中本机支持。

我正在尝试为服务类编写单元测试。我不确定如何为返回Uni / Multi的方法编写单元测试。

返回的方法Uni<String>

public Uni<String> hello(final String name) {
    final String message = "Hello " + name;
    return Uni.createFrom().item(message);
}

为上述方法实现的单元

@Test
void testHello() {
    final Uni<String> casePass = hello("Ram");
    // assertion passes and all good with this.
    casePass.subscribe().with(message -> Assertions.assertEquals("Hello Ram", message));
    
    final Uni<String> caseFail = hello("Ravan");
    //  It is expected to fail the assertion, and it does. But the test is not failing, instead aseertion fail message simply logged to the console.
    caseFail.subscribe().with(message -> Assertions.assertEquals("Hello Sita", message));
}

控制台日志

[-- Mutiny had to drop the following exception --]
Exception received by: io.smallrye.mutiny.helpers.UniCallbackSubscriber.onItem(UniCallbackSubscriber.java:71)
org.opentest4j.AssertionFailedError: expected: <Hello Sita> but was: <Hello Ram>
    at org.junit.jupiter.api.AssertionUtils.fail(AssertionUtils.java:55)
    at org.junit.jupiter.api.AssertionUtils.failNotEqual(AssertionUtils.java:62)
    at org.junit.jupiter.api.AssertEquals.assertEquals(AssertEquals.java:182)
    at org.junit.jupiter.api.AssertEquals.assertEquals(AssertEquals.java:177)
    at org.junit.jupiter.api.Assertions.assertEquals(Assertions.java:1124)
...
4

2 回答 2

1

有几种方法。您可以使用 smallrye.io/smallrye-mutiny/guides/testing 中提供的实用方法。但是,如果根据您的评论,您需要更多,我会推荐以下方法:

final Uni<Greeting> casePass = hello("Ram");
Greeting g = casePAss.await().atMost(Duration.ofSeconds(5)); // To be sure we don't stay tucked
// Assertions come here

所以基本上,你会阻止,直到项目被发送。避免await().indefinitely(),因为如果 Uni 从不发送项目,它可能会阻止您的测试。如果 Uni 发送失败,则不会await()...引发异常。

于 2021-07-14T06:53:24.627 回答
1

我真的建议使用 SmallRey 的测试方式。

https://smallrye.io/smallrye-mutiny/guides/testing

例如,您仍然可以从 multi/uni 使用调用中获取对象。

 public static Uni<String> hello(final String name) {
    final String message = "Hello " + name;
    return Uni.createFrom().item(message);
}

@Test
public void testUnit() {
    UniAssertSubscriber<String> tester = hello("someone")
            .invoke( i -> Assertions.assertEquals("Hello someone", i))
            .invoke(i -> Assertions.assertNotNull(i))
            .subscribe().withSubscriber(UniAssertSubscriber.create());
    tester.assertCompleted();
}

@Test
public void secondUnit() {
    UniAssertSubscriber<String> tester = hello("none")
            .invoke( i -> Assertions.assertEquals("Hello someone", i))
            .invoke(i -> Assertions.assertNotNull(i))
            .subscribe().withSubscriber(UniAssertSubscriber.create());
    tester.assertCompleted();
}

我希望你可以这样使用它

于 2021-07-28T18:39:48.533 回答