java-具有MockMvcBuilders独立设置的SpringBootTest尽管设置了它却没有加载我的ControllerAdvice
作者:互联网
我正在创建这样的控制器和控制器建议:
测试类别:
@RunWith(SpringRunner.class)
@SpringBootTest
public class TestController {
private MockMvc mockMvc;
@Mock
private MyService myService;
@Autowired
@InjectMocks
private MyController myController;
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
//Build the controller mock handler
mockMvc = MockMvcBuilders
.standaloneSetup(MyController.class)
.setControllerAdvice(new MyControllerAdvice())
//This also doesn't work
//.setHandlerExceptionResolvers(createExceptionResolver())
.build();
}
//This also did not work
private ExceptionHandlerExceptionResolver createExceptionResolver() {
ExceptionHandlerExceptionResolver exceptionResolver = new ExceptionHandlerExceptionResolver() {
protected ServletInvocableHandlerMethod getExceptionHandlerMethod(HandlerMethod handlerMethod, Exception exception) {
Method method = new ExceptionHandlerMethodResolver(MyControllerAdvice.class).resolveMethod(exception);
return new ServletInvocableHandlerMethod(new MyControllerAdvice(), method);
}
};
exceptionResolver.afterPropertiesSet();
return exceptionResolver;
}
/**
* Tests passing bad input to see if our exception handler is called.
*/
@Test
public void testBadRequest()
{
//Make a request object that has a bad input (e.g. bad date string)
MyRequest request = new MyRequest();
//Set the request values
request.setDate( "a" );
try
{
myController.getSomething( request );
}
catch (Exception e)
{
//It reaches here without ever reaching my controller advice in debugging
e.printStackTrace();
}
}
}
控制器建议:
@EnableWebMvc
@ControllerAdvice
@Component
public class MyControllerAdvice {
@ExceptionHandler(value = Exception.class)
public ResponseEntity<String> handleException(HttpServletRequest request, Exception exception) throws Exception
{
//This is never called (I'm using a debugger and have a breakpoint here)
return new ResponseEntity<String>(
"test",
HttpStatus.INTERNAL_SERVER_ERROR
);
}
}
解决方法:
您的示例中有两个问题:
> MockMvcBuilders#standaloneSetup()接收Controller对象作为参数,而不是Class对象.因此应该是:
mockMvc = MockMvcBuilders
.standaloneSetup(new MyController())
.setControllerAdvice(new MyControllerAdvice())
.build();
>您正在直接调用myController.getSomething(request),而您应该使用先前构建的模拟Mvc.不建议使用DirectDis,因为它不使用TestDispatcherServlet处理.这是模拟嘲笑请求的几个例子:
得到
mockMvc.perform(get("/testSomething"))
.andExpect(status().is5xxServerError())
.andReturn();
开机自检
mockMvc.perform(post("/testSomething")
.contentType(MediaType.APPLICATION_JSON)
.content(json)) //it's JSON string
.andExpect(status().is5xxServerError())
.andReturn();
标签:spring-boot-test,spring-boot,spring,java,spring-mvc 来源: https://codeday.me/bug/20191025/1930532.html