This example shows how to write junit test for a method that returns Flux of Order objects.
StepVerifier from io.projectreactor.reactor-test is used to test reactive components.
Below is the Service class that returns Flux of three Order objects.
OrderService.java
package com.kswaughs.webflux;
import java.util.ArrayList;
import java.util.List;
import com.kswaughs.webflux.model.Order;
import reactor.core.publisher.Flux;
public class OrderService {
public Flux<Order> getOrders() {
List<Order> orders = new ArrayList<>();
orders.add(buildOrder(345, 30, "DELIVERED"));
orders.add(buildOrder(654, 50, "IN-TRANSIT"));
orders.add(buildOrder(999, 12, "DELIVERED"));
// return flux of orders..
return Flux.fromIterable(orders);
}
private Order buildOrder(int orderId, double amount, String status) {
Order order = new Order();
order.setOrderId(orderId);
order.setAmount(amount);
order.setStatus(status);
return order;
}
}
Below is the Junit test class to test Flux of objects using StepVerifier
SpringWebFluxExampleTest.java
package com.kswaughs.webflux;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import com.kswaughs.webflux.model.Order;
import reactor.core.publisher.Flux;
import reactor.test.StepVerifier;
public class SpringWebFluxExampleTest {
private OrderService orderService = new OrderService();
@Test
public void testGetOrders() {
Flux<Order> orders = orderService.getOrders();
StepVerifier.create(orders)
// Above method is returning three orders.
// we are asserting on first order only.
.assertNext(order -> {
assertEquals(Integer.valueOf(345), Integer.valueOf(order.getOrderId()));
assertEquals(Double.valueOf(30), Double.valueOf(order.getAmount()));
assertEquals("DELIVERED", order.getStatus());
})
// verifying count of next orders.
.expectNextCount(2)
.verifyComplete();
}
}
pom.xml
<dependency>
<groupId>io.projectreactor</groupId>
<artifactId>reactor-test</artifactId>
<scope>test</scope>
</dependency>