如何在单元测试的控制器建议中模拟服务

时间:2017-03-29 07:12:46

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

问题是我无法对此进行单元测试/模拟,因为控制器建议中的 messageByLocaleService 为空。请建议任何方式注入messageByLocaleSerI的模拟都有这样的设置:

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设置&amp;测试方法:

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

1 个答案:

答案 0 :(得分:2)

从您显示的代码中判断一下有点难,但可以假设您正在测试ExceptionControllerAdvice并在单元测试中的某处创建实例。如果您这样做,请尝试以下操作 @InjectMocks private ExceptionControllerAdvice unitUnderTest; @Mock private MessageByLocaleService messageByLocaleService;

我相信Mockito将创建MessageByLocaleService的模拟并自动将其注入您的ExceptionControllerAdvice。