2017-03-29 2 views
0

문제는 messageByLocaleService컨트롤러 조언의 null 때문에 내가하지 단위 테스트 /이 조롱 할 수 있습니다에 대한 컨트롤러 조언 내부의 서비스를 모의한다. 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을 설정 & 테스트 방법 :

@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

코드에서 알기는 약간 어렵지만, 아마도 ExceptionControllerAdvice을 테스트하고 단위 테스트의 어딘가에 인스턴스를 만듭니다. 그럴 경우 다음을 시도하십시오. @InjectMocks private ExceptionControllerAdvice unitUnderTest; @Mock private MessageByLocaleService messageByLocaleService;

나는 Mockito가 MessageByLocaleService의 모의를 작성하고이를 ExceptionControllerAdvice에 자동 삽입한다고 생각합니다.

+0

내 단위 테스트 클래스에서 이것을 추가했습니다. 제안 해 주셔서 감사합니다. – nanospeck