【问题标题】:SpringBootTest with MockMvcBuilders stand alone setup is not loading my ControllerAdvice despite setting it带有 MockMvcBuilders 独立设置的 SpringBootTest 没有加载我的 ControllerAdvice,尽管设置了它
【发布时间】:2017-09-17 22:55:55
【问题描述】:

我正在创建这样的控制器和控制器建议:

测试类:

@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
        );
    }
}

【问题讨论】:

  • 观察但混合了 SpingBootTest 和 MockMvc - 我很欣赏它可以在 java 中完成。如果您有 SpringBootTest 提供的正在运行的测试应用程序,则通过请求/响应测试服务。使用 MockMvc 作为第二个测试来测试你的 Controller 类的细节。

标签: java spring spring-mvc spring-boot spring-boot-test


【解决方案1】:

您的示例中有两个问题:

  1. MockMvcBuilders#standaloneSetup() 接收 Controller 对象作为参数,而不是 Class 对象。所以应该是:

    mockMvc = MockMvcBuilders
            .standaloneSetup(new MyController())
            .setControllerAdvice(new MyControllerAdvice())
            .build();
    
  2. 您正在直接调用myController.getSomething( request ),而您应该使用以前构建的mockMvc。不建议直接调用,因为它没有使用TestDispatcherServlet 处理。以下是mockMvc 请求的几个示例:

获取

    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();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-03-23
    • 2018-10-24
    • 1970-01-01
    • 2012-05-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多