Home > database >  How to use StepVerifier to process a list of products using the Webflux reactive framework
How to use StepVerifier to process a list of products using the Webflux reactive framework

Time:10-25

I have list of products returned from a controller as a Flux. I am able to verify the count but I don't know how to verify the individual products. The product has a lot of properties so I do want to do a direct equals which may not work. Here is a subset of the properties of the class. The repository layer works fine and returns the data. The problem is that I don't know how to use the StepVerifier to validate the data returned by the ProductService. I am using a mock ProductRepository not shown as it just mocks return a Flux of hardcoded products like this Flux.just(productData)


    import java.time.LocalDateTime;
    import java.util.List;

    public class ProductData {
    
      static class Order {
        String orderId;
        String orderedBy;
        LocalDateTime orderDate;
        List<OrderItem> orderItems; 
     }
    
      static class OrderItem {
        String itemCode;
        String name;
        int quantity;
        int quantityOnHold;
        ItemGroup group;
     }
    
      static class ItemGroup{
        String category;
        String warehouseID;
        String warehoueLocation;
     }
  }


Here is the service class.


     import lombok.RequiredArgsConstructor;
     import reactor.core.publisher.Flux;

     @RequiredArgsConstructor
     public class ProductService {
        final ProductRepository productRepository;
        Flux<ProductData> findAll(){
        return productRepository.findAll();
      }
    }


CodePudding user response:

Since your example ProductData class doesn't have any fields to verify, let's assume it has one order field:

    public class ProductData {
    
      Order order;

      //rest of the code
  }

Then fields can be verified like this:

    @Test
    void whenFindAllThenReturnFluxOfProductData() {
        Flux<ProductData> products = productRepository.findAll();
        StepVerifier.create(products)
                .assertNext(Assertions::assertNotNull)
                .assertNext(product -> {
                    ProductData.Order order = product.order;
                    LocalDateTime expectedOrderDate = LocalDateTime.now();
                    assertNotNull(order);
                    assertEquals("expectedOrderId", order.orderId);
                    assertEquals(expectedOrderDate, order.orderDate);
                    //more checks
                }).assertNext(product -> {
                    List<ProductData.OrderItem> orderItems = product.order.orderItems;
                    int expectedSize = 12;
                    assertNotNull(orderItems);
                    assertEquals( expectedSize, orderItems.size());
                    //more checks
                })
                .expectComplete()
                .verify();
    }

  • Related