By kswaughs | Tuesday, June 9, 2020

Spring WebFlux Junit Test Example

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.
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();
       return order;

Below is the Junit test class to test Flux of objects using StepVerifier
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();

    public void testGetOrders() {
        Flux<Order> orders = orderService.getOrders();
            // 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.


Useful Links

Spring WebFlux Mono Junit Test Example

Recommend this on