I am using Smallrye Mutiniy reactive library in my Quarks application as it is supported natively in Quarks applications.
I'am trying to write unit tests for a service class. I am not sure how to write unit tests for a method that returns Uni/Multi.
A method returning Uni<String>
public Uni<String> hello(final String name) {
final String message = "Hello " + name;
return Uni.createFrom().item(message);
}
Unit implemented for the above method
@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));
}
Console logs
[-- 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)
...
I would really recommend using the way of testing from SmallRey.
https://smallrye.io/smallrye-mutiny/1.7.0/guides/testing/
You still can get the object out of the multi/uni use invoke, for example.
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();
}
I hope you can use it like that
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With