我最近遇到了同样的错误,我没有使用 MockMVC,而是创建了一个集成测试,如下所示:
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@ContextConfiguration(classes = { MyTestConfiguration.class })
public class MyTest {
@Autowired
private TestRestTemplate testRestTemplate;
@Test
public void myTest() throws Exception {
ResponseEntity<String> response = testRestTemplate.getForEntity("/test", String.class);
assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, response.getStatusCode(), "unexpected status code");
}
}
和
@Configuration
@EnableAutoConfiguration(exclude = NotDesiredConfiguration.class)
public class MyTestConfiguration {
@RestController
public class TestController {
@GetMapping("/test")
public ResponseEntity<String> get() throws Exception{
throw new Exception("not nice");
}
}
}
这篇文章很有帮助:https ://github.com/spring-projects/spring-boot/issues/7321