使用MockMVC在JUnitTest中注册@ControllerAdvice带注释的控制器 [英] Register @ControllerAdvice annotated Controller in JUnitTest with MockMVC

查看:270
本文介绍了使用MockMVC在JUnitTest中注册@ControllerAdvice带注释的控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的@ControllerAdvice带注释的Controller看起来像这样:

My @ControllerAdvice annotated Controller looks like this:

@ControllerAdvice
public class GlobalControllerExceptionHandler {

    @ResponseStatus(value = HttpStatus.UNAUTHORIZED)
    @ExceptionHandler(AuthenticationException.class)
    public void authenticationExceptionHandler() {
    }
}

当然,我的开发是测试驱动的,我想在JUnit Tests中使用我的异常处理程序.我的测试用例看起来像这样:

Of course my development is test driven and I would like to use my exception Handler in the JUnit Tests. My Test case looks like this:

public class ClientQueriesControllerTest {

    private MockMvc mockMvc;

    @InjectMocks
    private ClientQueriesController controller;

    @Mock
    private AuthenticationService authenticationService;

    @Before
    public void setup() {
        MockitoAnnotations.initMocks(this);
        mockMvc = MockMvcBuilders.standaloneSetup(controller).build();
    }

    @Test
    public void findAllAccountRelatedClientsUnauthorized() throws Exception {
        when(authenticationService.validateAuthorization(anyString())).thenThrow(AuthenticationException.class);

        mockMvc.perform(get("/rest/clients").header("Authorization", UUID.randomUUID().toString()))
                .andExpect(status().isUnauthorized());
    }
}

可能我需要注册ControllerAdvice类.该怎么做?

Probably I need to register the ControllerAdvice Class. How to do that?

推荐答案

从Spring 4.2开始,您可以将ControllerAdvice直接注册到StandaloneMockMvcBuilder中:

Since Spring 4.2, you can register your ControllerAdvice directly into your StandaloneMockMvcBuilder:

MockMvcBuilders
     .standaloneSetup(myController)
     .setControllerAdvice(new MyontrollerAdvice())
     .build();

这篇关于使用MockMVC在JUnitTest中注册@ControllerAdvice带注释的控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆