I am testing a Spring boot MVC application which takes MultipartFile as input. My service class will throw a custom exception when the file format is other than .json. I've written a JUnit test case which tests this scenario.
Instead of throwing my custom exception (expected = FileStorageException.class)
my test case is throwing an AssertionError
.
How to resolve this issue and validate the exception message using .andExpect(content().string("Wrong file format. Allowed: JSON."))
Exception
09:36:48.327 [main] DEBUG org.springframework.test.web.servlet.TestDispatcherServlet - Could not complete request com.test.util.exception.FileStorageException: Wrong file format. Allowed: JSON.
Code
@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());
}
}
}