0

我正在测试一个以 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());
    }
  }
}
4

1 回答 1

0

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
}

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

于 2018-10-01T17:54:34.427 回答