简体   繁体   中英

How can I call a method which takes a parameter of type ServerHttpResponse?

I am writing a Junit Test Case with @WebFluxTest for a Service class.

Since I need to test a method for a Service Class I need to call the method and check whether it returns a correct Http Status ie 200/"OK", and I need help regarding the same.

Service Class Method which I want to test:

public Mono<Product> addProduct(Product productData, ServerHttpResponse response) {
        productData.getFcData().replaceAll((fcCode,fcData)-> {
                fcData.setBatchWiseData(fcData.getBatchWiseData().parallelStream()
                    .map(d->{
                        if(d.getLastUpdated() ==null)
                            d.setLastUpdated(LocalDateTime.now());
                        return d;
                    } ).collect(Collectors.toList()));
                    return fcData;
            }
        );
        
        Mono<Boolean> success = redisTemplate.opsForHash()
                .put(PRODUCT_PREFIX+productData.getProductCode(), 
                        productData.getProductCode(), productData);
            success.subscribe();
            response.setStatusCode(HttpStatus.CREATED);
        return success.flatMap(x->getProduct(productData.getProductCode()));
    }

My test case:

    @Test
    void testAddProduct(){
        Product prodObj = new Product();
        prodObj.setProductCode("789123");

        FcWiseData fcWiseDataObj = new FcWiseData();
        fcWiseDataObj.setFcCode("50001");
        BatchWiseData batchWiseDataObj = new BatchWiseData();
        batchWiseDataObj.setBatchNo("Uni001");
        batchWiseDataObj.setExpiryDate(LocalDate.of(2020, 1, 8));
        batchWiseDataObj.setMrp(100.0);
        batchWiseDataObj.setStockQty(1L);
        batchWiseDataObj.setLastUpdated(LocalDateTime.of(2021, Month.JULY, 29, 19, 30, 40));
        fcWiseDataObj.setBatchWiseData(List.of(batchWiseDataObj));
        Map<String, FcWiseData> fcDataObj = Map.of("52001", fcWiseDataObj);
        prodObj.setFcData(fcDataObj);

        Mockito.when(redisTemplate.opsForHash()).thenReturn(hashOperations);
        Mockito.doReturn(Mono.just(true)).when(hashOperations)
        .put("Product" + prodObj.getProductCode(), prodObj.getProductCode(), prodObj);
        
    //  ServerHttpResponse response = Mockito.mock(ServerHttpResponse.class);
    //  assertNotNull(prodService.addProduct(prodObj, response));
         
    // what should I write here to test the above method?   
    }

You can use the class MockHttpServletResponse for the method params in your tests.

Something like this should work.

HttpServletResponse httpServletResponse = new MockHttpServletResponse();

For more details, please refer to the javadoc here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM