繁体   English   中英

如何调用采用 ServerHttpResponse 类型参数的方法?

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

我正在使用 @WebFluxTest 为服务 class 编写一个 Junit 测试用例。

由于我需要测试服务 Class 的方法,我需要调用该方法并检查它是否返回正确的 Http 状态,即 200/“OK”,我需要有关相同的帮助。

Service Class 我要测试的方法:

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()));
    }

我的测试用例:

    @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?   
    }

您可以将 class MockHttpServletResponse用于测试中的方法参数。

这样的事情应该有效。

HttpServletResponse httpServletResponse = new MockHttpServletResponse();

有关详细信息,请参阅此处的 javadoc

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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