Issue
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 i.e. 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?
}
Solution
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
Answered By - Parth Manaktala
Answer Checked By - Terry (JavaFixing Volunteer)