Home > Enterprise >  Junit Test for exception and WebRequest
Junit Test for exception and WebRequest

Time:12-31

I'm a beginner and i'm writing unittests and I've stumbled across something I can't find a solution for that fits my needs.

I want to write some Junit Test for that exceptions.

There is my class with my Method

@ControllerAdvice
@RestController
public class CustomizedResponseEntityExceptionHandler extends ResponseEntityExceptionHandler {

    @ExceptionHandler(MethodArgumentTypeMismatchException.class)
    public final ResponseEntity<AccessError> numberFormatExceptionNotFoundException(
                MethodArgumentTypeMismatchException ex, NumberFormatException exe, WebRequest request) {
            AccessError errorDetails = new AccessError();
            errorDetails.code("400");
            errorDetails.addErrorsItem(new Error("400",ex.getMessage()));
            errorDetails.setCode("400");
            errorDetails.setTimestamp(new Date().toInstant().atOffset(ZoneOffset.UTC));
            errorDetails.setMessage(HttpStatus.BAD_REQUEST.getReasonPhrase());
            errorDetails.setPath(((ServletWebRequest) request).getRequest().getRequestURI());
            return new ResponseEntity<>(errorDetails, HttpStatus.BAD_REQUEST);
        }
    @Override
    protected ResponseEntity<Object> handleHttpMediaTypeNotSupported(HttpMediaTypeNotSupportedException ex,
            HttpHeaders headers, HttpStatus status, WebRequest request) {
        AccessError errorDetails = new AccessError();
        errorDetails.code("400");
        errorDetails.addErrorsItem(new Error("400","Media Type Not Supported Exception"));
        errorDetails.setCode("400");
        errorDetails.setTimestamp(new Date().toInstant().atOffset(ZoneOffset.UTC));
        errorDetails.setMessage(HttpStatus.BAD_REQUEST.getReasonPhrase());
        errorDetails.setPath(((ServletWebRequest) request).getRequest().getRequestURI());
        return new ResponseEntity<>(errorDetails, HttpStatus.BAD_REQUEST);
    }

And there is my testClass :

public class CustomizedResponseEntityExceptionHandlerTest {
@Mock
ResponseEntity<AccessError> responseEntity;
WebRequest webRequest;

@InjectMocks
private CustomizedResponseEntityExceptionHandler custom = new CustomizedResponseEntityExceptionHandler();

@Test
public void numberFormatExceptionNotFoundExceptionTest() {

    WebRequest webRequest;
    String msg = "toto";
    AccessError errors = new AccessError();
    errors.setPath("app");
    errors.getPath();
    errors.setTimestamp(new Date().toInstant().atOffset(ZoneOffset.UTC));
    errors.timestamp(new Date().toInstant().atOffset(ZoneOffset.UTC));
    ApiException apiException = new ApiException(errors, msg);
    
    ResponseEntity<AccessError> responseApi = custom.handleUserNotFoundException(apiException, webRequest.getHeaderNames());
    assertThatExceptionOfType(ApiException.class);

}

My Question is : How i can do a JUnit Test for that cases, which have webRequest and some exceptions ?

I've tried a lot of thing but i think i don't have the right thinking method.

Thanks !!

CodePudding user response:

You can use MockMvc to test your API for success/failure or any other custom response such as 404 Not found

A Sample snippet for example would look like this

public class MyTestClass{

  @Autowired
  private MockMvc mvc;
 @Test
  public void testMethod()  {
       MvcResult result = mvc.perform(post("/yourEndPoint")
      .contentType("application/json")      //Optional depending on your API Design
      .content(content))      //Optional depending on your API Design
      .andExpect(status().isOk())   //isOk , isBadRequest()  and so on 
      .andReturn();
}
} //End of class

Refer this article which explains in a simple manner

https://howtodoinjava.com/spring-boot2/testing/spring-boot-mockmvc-example/

CodePudding user response:

I found the solution

private CustomizedResponseEntityExceptionHandler test = new CustomizedResponseEntityExceptionHandler();
MockHttpServletRequest servletRequest = new MockHttpServletRequest();
@Test
public void numberFormatExceptionNotFoundExceptionTest() {
    MethodArgumentTypeMismatchException expt = null ;
    NumberFormatException exe = null;
    servletRequest.setServerName("www.example.com");
    servletRequest.setRequestURI("/v1/someuri");
    servletRequest.addParameter("brand1", "value1");
    servletRequest.addParameter("brand2", "value2");
    WebRequest webRequest = new ServletWebRequest(servletRequest);
    ResponseEntity<AccessError> result = test.numberFormatExceptionNotFoundException(expt,exe, webRequest);
    assertNotNull(result);
}
  • Related