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