【问题标题】:Junit Test for exception and WebRequest异常和 WebRequest 的 Junit 测试
【发布时间】:2021-12-30 08:57:30
【问题描述】:

我是一个初学者,我正在编写单元测试,但我偶然发现了一些我无法找到适合我需要的解决方案。

我想为该异常编写一些 Junit 测试。

我的课有我的方法

@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);
    }

还有我的 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);

}

我的问题是:我如何为那些有 webRequest 和一些异常的案例做 JUnit 测试?

我尝试了很多东西,但我认为我没有正确的思维方式。

谢谢!!

【问题讨论】:

    标签: java spring-boot exception junit webrequest


    【解决方案1】:

    您可以使用 MockMvc 测试您的 API 是否成功/失败或任何其他自定义响应,例如 404 Not found

    例如,Sample sn-p 看起来像这样

    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
    

    请参阅这篇文章,它以简单的方式解释

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

    【讨论】:

    • 我试过了,但我认为这不是我想要的。我只想测试我的 API 的异常部分,我猜没有端点。还是谢谢!
    【解决方案2】:

    我找到了解决办法

    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);
    }
    

    【讨论】:

      猜你喜欢
      • 2011-01-28
      • 1970-01-01
      • 2013-02-19
      • 1970-01-01
      • 1970-01-01
      • 2020-05-13
      • 2015-11-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多