【问题标题】:Java test for an exceptionJava 测试异常
【发布时间】:2020-01-26 15:55:03
【问题描述】:

我有一个使用这种方法的课程

@Test
public void testWithOriginalPattern() throws Exception {
  this.OBJCET_CONTENT =
      "{\"service_instance\": \"foo\", \"notifications\": {\"subject\": \"bar0-9A-Za-z-._\"}}";
  final HttpServletRequest request = createGoodRequest(this.OBJCET_CONTENT);
  final ContainerMetadataManagementServlet containerMetadataManagementServlet =
      new MockContainerMetadataManagementServlet();
  assertNotNull(containerMetadataManagementServlet.runGetConfig(request, "/service-api-create-bucket-schema.json"));
}

我现在想对主题中的无效字符进行测试。发生这种情况时会引发以下异常:

HttpException(400,{"status_code":400,"error_code":"MalformedNotificationsError","uri":"uri","message":"The provided JSON was not well-formed or did not validate against the published schema."},null)

我该如何测试?

【问题讨论】:

标签: java unit-testing testing exception junit


【解决方案1】:

修改你的测试方法,如下代码:

@Test(expected = StatusRuntimeException.class)
public void test01() 
{
  containerMetadataManagementServlet.runGetConfig(request,"/service-api-create-bucket-schema.json");
}

【讨论】:

    【解决方案2】:

    Junit5 允许您使用 Java8 Lambda 语法断言Throws:https://howtodoinjava.com/junit5/expected-exception-example

    他们的例子:

    @Test
    void testExpectedException() {
    
      Assertions.assertThrows(NumberFormatException.class, () -> {
        Integer.parseInt("One");
      });
    
    }
    

    【讨论】:

      【解决方案3】:

      我用@Test(expected = ServiceException.class)解决了这个问题

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-04-11
        • 1970-01-01
        • 2014-07-07
        • 2011-01-28
        • 2012-09-27
        • 2016-08-11
        • 1970-01-01
        相关资源
        最近更新 更多