【问题标题】:How to Mock a service inside Controller Advice for Unit Testing如何在 Controller Advice 中模拟服务以进行单元测试
【发布时间】:2017-03-29 07:12:46
【问题描述】:

问题是我无法对它进行单元测试/模拟,因为 messageByLocaleServiceController Advice 中为空。请提出任何注入 messageByLocaleSer 模拟的方法我有这样的设置:

ExceptionControllerAdvice 类:

@Autowired
private MessageByLocaleService messageByLocaleService; //CANNOT MOCK THIS

@ControllerAdvice
public class ExceptionControllerAdvice {

    @ExceptionHandler(UserNotFoundException.class)
    public ResponseEntity<String> handleUnexpectedException(HttpServletRequest request, Exception e) {

        //build response as below
        String s = messageByLocaleService.buildMessage(HttpStatus.ERROR,"User Not Valid"); // GETTING NULL HERE
        //and send the response back to the client here
    }
}

控制器方法:

@RequestMapping(value = "${foo.controller.requestMappingUrl.login}",
                                 method = RequestMethod.POST)
public ResponseMessage<String> loginUser(
            @RequestParam("username") String username,
               HttpServletRequest httpServletRequest,
               HttpServletResponse httpServletResponse) throws Exception {

       return fooService.login(username);
}

JUnit 设置和测试方法:

@InjectMocks
private ProjectController projectController;

@Mock
private FooService fooService;


@Mock
private MessageByLocaleService messageByLocaleService;

@Before
    public void setUp() throws Exception {
        MockitoAnnotations.initMocks(this);
    mockMvc = MockMvcBuilders.standaloneSetup(projectController)
                .setMessageConverters(new MappingJackson2HttpMessageConverter())
                .setControllerAdvice(new ExceptionControllerAdvice()).build();
}


@SuppressWarnings("unchecked")
@Test
    public void testControllerUserNotFoundException() throws Exception {
        Response resp = new Response();
        resp.setStatusCode(StatusCode.UserNotFoundErrorCode);
        when(fooService.login(any(String.class)).
        thenThrow(UserNotFoundException.class);

        mockMvc.perform(post("/service-user/1.0/auth/login?&username=test")
                        .contentType(contentType)).
     andExpect(status().isNotAcceptable())
                .andExpect(jsonPath("$.statusCode", is("ERRORCODE144")));
}

【问题讨论】:

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


    【解决方案1】:

    从您展示的代码中很难看出,但大概您正在测试ExceptionControllerAdvice 并在您的单元测试中的某处创建一个实例。如果这样做,请尝试以下操作 @InjectMocks private ExceptionControllerAdvice unitUnderTest; @Mock private MessageByLocaleService messageByLocaleService;

    我相信 Mockito 会创建 MessageByLocaleService 的 Mock 并将其自动注入到您的 ExceptionControllerAdvice 中。

    【讨论】:

    • 在我的单元测试类中添加它是有效的。感谢您的建议。
    猜你喜欢
    • 2017-06-25
    • 1970-01-01
    • 1970-01-01
    • 2016-11-09
    • 2015-11-29
    • 2020-02-08
    • 1970-01-01
    • 2011-08-08
    • 1970-01-01
    相关资源
    最近更新 更多