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 ($ == at, i don't know why but the editor doesn't accept at):
$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 = "test"; 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 !!