【问题标题】:Spring Boot JUnit test case to test custom exception is throwing AssertionError instead of CustomException用于测试自定义异常的 Spring Boot JUnit 测试用例抛出 AssertionError 而不是 CustomException
【发布时间】:2019-03-06 17:58:28
【问题描述】:

我正在测试一个以 MultipartFile 作为输入的 Spring Boot MVC 应用程序。当文件格式不是 .json 时,我的服务类将引发自定义异常。我编写了一个 JUnit 测试用例来测试这个场景。

我的测试用例不是抛出我的自定义异常(expected = FileStorageException.class),而是抛出AssertionError

如何解决此问题并使用.andExpect(content().string("Wrong file format. Allowed: JSON.")) 验证异常消息

例外

09:36:48.327 [main] 调试 org.springframework.test.web.servlet.TestDispatcherServlet - 无法完成请求 com.test.util.exception.FileStorageException:错误的文件格式。允许:JSON。

代码

@WebAppConfiguration
@ContextConfiguration(classes = WebConfig.class, initializers = ConfigFileApplicationContextInitializer.class)
@RunWith(SpringJUnit4ClassRunner.class)
public class UploadTest
{

  @Autowired
  private WebApplicationContext webApplicationContext;

  private MockMvc mockMvc;

  @Before
  public void setup()
  {
    mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
  }

  /**
   * 
   */
  public UploadTest()
  {
    // default constructor
  }

  @Test(expected = FileStorageException.class)
  // @Test(expected= AssertionError.class)
  public void testInvalidFileFormat() throws Exception
  {
    try
    {
      MockMultipartFile testInput = new MockMultipartFile("file", "filename.txt", "text/plain", "some json".getBytes());
      mockMvc.perform(MockMvcRequestBuilders.multipart("/uploadFile").file(testInput))
          // .andExpect(status().isInternalServerError()).andExpect(content().string("Wrong
          // file format. Allowed: JSON."))
          .andDo(print());
    }
    catch (Exception e)
    {
      fail(e.toString());
    }
  }
}

【问题讨论】:

    标签: spring spring-boot junit custom-exceptions


    【解决方案1】:

    JUnit 只知道测试方法抛出的异常(在您的示例中为 testInvalidFileFormat()。因此它只能检查这些异常。

    您正在捕获mockMvc.perform(...) 抛出的每个异常,而是从该行中抛出一个AssertionError

    fail(e.toString());
    

    这是您在测试结果中看到的AssertionError

    如果你想测试异常,那么你不能在你的测试中捕获它们:

    @Test(expected = FileStorageException.class)
    public void testInvalidFileFormat() throws Exception
    {
      MockMultipartFile testInput = new MockMultipartFile(
        "file", "filename.txt", "text/plain", "some json".getBytes()
      );
      mockMvc.perform(MockMvcRequestBuilders.multipart("/uploadFile").file(testInput))
          // .andExpect(status().isInternalServerError()).andExpect(content().string("Wrong
          // file format. Allowed: JSON."))
          .andDo(print());
    }
    

    顺便说一句,你不需要显式添加默认构造函数并且可以删除行

    /**
     * 
     */
    public UploadTest()
    {
        // default constructor
    }
    

    它被称为默认构造函数,因为它自动存在。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-08-27
      • 1970-01-01
      • 2019-01-29
      • 2018-02-23
      • 2013-11-01
      • 2018-06-27
      • 1970-01-01
      • 2021-10-13
      相关资源
      最近更新 更多