`ErrorController` will not be called when test using `MockMvc`
We are building a project using spring boot (v1.3.3.RELEASE), we have a custom ErrorController which look like this
@RestController
@RequestMapping("/error")
public class GlobalErrorController extends AbstractErrorController {
@Autowired
public GlobalErrorController(ErrorAttributes errorAttributes) {
super(errorAttributes);
}
@Override
public String getErrorPath() {
return "/error";
}
@RequestMapping(produces = MediaType.ALL_VALUE)
public ResponseEntity error(HttpServletRequest request) {
HttpStatus status = getStatus(request);
if (status.is5xxServerError()) {
//log maybe
}
return new ResponseEntity(status);
}
}
We find it worked well when we start the spring boot application, and try to access it through curl or browser, it just responds the status code and no body(content).
But when we tried to write an integration test for this controller, we found out that the ErrorController will never be called, some sample code lies here:
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = {MyApplication.class, TestConfiguration.class})
@WebAppConfiguration
public class GlobalErrorControllerIntegrationTest {
private MockMvc mockMvc;
@Autowired
private WebApplicationContext wac;
@Before
public void setUp() throws Exception {
mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
}
@Test
public void shouldRespondWithServerErrorButNoContent() throws Exception {
mockMvc.perform(get("/test/err")).andExpect(status().is5xxServerError()).andExpect(content().string(""));
}
}
MyApplication is the entry of the application which is annotated with @SpringBootApplication, and TestConfiguration is some test fixtures which will be used to help run the test, it looks like this:
@Configuration
@ComponentScan("com.my.test.fixtures")
public class TestConfiguration {
}
and also we have a test controller which will raise an error
@RestController
public class TestErrorController {
@RequestMapping("/test/err")
public int raiseError() {
return 1 / 0;
}
}
Can somebody help to figure out whats the problem?
And we are also curious about how ErrorController worked, we have ever tried to debug and figure out, but the stack is too deep to follow. We are wondering if you can supply some documentation of that to help developers have a better understanding.
Thanks advance.
Is that caused due to no embedded server when using spring's TestContext?
Thanks for getting in touch, but it feels like this is a question that would be better suited to Stack Overflow. As mentioned in the guidelines for contributing, we prefer to use GitHub issues only for bugs and enhancements. Feel free to update this issue with a link to the re-posted question (so that other people can find it) or add some more details if you feel this is a genuine bug.
so link - http://stackoverflow.com/questions/36690738/spring-boot-errorcontroller-will-not-be-called-when-test-using-mockmvc