我需要为用@RestControllerAdvice注释的类编写一个JUnit测试用例。尝试了一下,但是我遇到了一个错误
org.mockito.exceptions.misusing.MissingMethodInvocationException: when()需要一个参数,该参数必须是“模拟的方法调用”。 例如: when(mock.getArticles())。thenReturn(articles);
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler({NumberFormatException.class, NoHandlerFoundException.class})
public ResponseEntity<ExceptionJSONInfo> handleGenericException(HttpServletRequest request, Exception ex) {
ExceptionJSONInfo empExce = new ExceptionJSONInfo();
empExce.setMessage(ex.getMessage().trim());
empExce.setUrl(request.getRequestURL().toString());
empExce.setStatusCode(HttpStatus.BAD_REQUEST.toString());
return ResponseEntity.badRequest().body(empExce);
}
}
@Data
public class ExceptionJSONInfo {
private String url;
private String statusCode;
private String message;
}
我尝试过
@RunWith(MockitoJUnitRunner.class)
public class GlobalExceptionHandlerTest {
MockHttpServletRequest request;
Exception exception;
@InjectMocks
GlobalExceptionHandler gitService= new GlobalExceptionHandler();
ExceptionJSONInfo empExce = new ExceptionJSONInfo();
@Before
public void setUp() {
request = new MockHttpServletRequest("GET","http://localhost:7777/rest/v1/gitrepo/ff");
exception = new Exception("Failed to convert value of type 'java.lang.String' to required type 'int'; "
+ " nested exception is java.lang.NumberFormatException: For input string: \\\"ff\\\"");
empExce.setMessage(exception.getMessage().trim());
empExce.setUrl(request.getRequestURL().toString());
empExce.setStatusCode(HttpStatus.BAD_REQUEST.toString());
}
@Test
public void test() {
when(gitService.handleGenericException(request, exception)).thenReturn(ResponseEntity.badRequest().body(empExce));
ResponseEntity<ExceptionJSONInfo> result = gitService.handleGenericException(request, exception);
assertEquals(HttpStatus.BAD_REQUEST.toString(),result.getBody().getStatusCode());
}
}