0
votes

I'm writing unit test for controller, this time I purposely made a request which will trigger ConstrainViolationException, in mockmvc instead of expect it throws the error. How can I tell spring not to throw it and let mvcresult verify the result

Here is my code snippet

@WebMvcTest(ProductController.class)
public class ProductControllerTest {

    @Autowired
    private MockMvc mockMvc;

    @MockBean
    private ProductService productService;

    @Test
    public void createProduct_With_InvalidRequest_ShouldReturn_BadRequest() throws Exception {

        ProductWebRequest productWebRequest = ProductWebRequest.builder()
                .sku(null)
                .productName(null)
                .barcode(null)
                .build();

        ProductServiceWebRequest productServiceWebRequest = ProductServiceWebRequest.builder()
                .sku(productWebRequest.getSku())
                .productName(productWebRequest.getProductName())
                .barcode(productWebRequest.getBarcode())
                .build();

        ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
        String json = ow.writeValueAsString(productWebRequest);

        BDDMockito.given(productService.createProduct(productServiceWebRequest)).willThrow(ConstraintViolationException.class);

        mockMvc.perform(MockMvcRequestBuilders.post("/v1/products")
                .contentType(MediaType.APPLICATION_JSON).content(json))
                .andExpect(MockMvcResultMatchers.status().isBadRequest())
                .andExpect(mvcResult -> Assertions.assertTrue(mvcResult.getResolvedException() instanceof ConstraintViolationException));
    }
}

And this is the error that appears

(ProductControllerTest.java:50)
Caused by: javax.validation.ConstraintViolationException

I know this will throw an exception, but how can I use that exception in the expect section for assertions?

1
Can you add print method in mvc to see the response of request?huy

1 Answers

0
votes

ConstraintValidationException is a bit of special case.

To ensure that its handled properly you can do like this ...

@Before
    public void setup() throws Exception {
        this.mockMvc = standaloneSetup(new MyController())
                .setControllerAdvice(new CustomExceptionHandler(), new ConstraintViolationsHandler())
                .build();
    }

Does this solve your problem ? Tell me in the comments.