2017-03-10 1 views
0

단위 코드를 내 Presenter 단위 테스트하려고합니다. 코드에서 알 수 있듯이 Retrofit 요청을 만들고 있는데 응답이 성공하면 View에서 메서드를 호출합니다.단위 테스트 발표자의 비즈니스 로직

내 발표자의

코드 내가 테스트 할 :

@Mock 
private ChatMVP.View view; 

@Mock 
private GetChatroomsService getChatroomsService; 

@Mock 
private RequestBody requestBody; 

@Mock 
private Call<GetChatroomsServiceResponse> call; 

@Captor 
private ArgumentCaptor<Callback<GetChatroomsServiceResponse>> callback; 

@Mock 
private List<GetChatroomsResponseNestedItem> chatroomsResponseNestedItems; 

private String accountId = "14"; 
private String apiToken = "someToken"; 

private ChatPresenter chatPresenter; 

@Before 
public void setUp() throws Exception { 
    MockitoAnnotations.initMocks(this); 

    chatPresenter = new ChatPresenter(view, getChatroomsService, apiToken); 

} 

@Test 
public void onLoadChatrooms() throws Exception { 
    when(getChatroomsService.getChatrooms(apiToken, requestBody)) 
      .thenReturn(call); 

    chatPresenter.onLoadChatrooms(accountId, "0"); 

    verify(call).enqueue(callback.capture()); 
    callback.getValue().onResponse(call, getResponse()); 

    verify(view).showData(chatroomsResponseNestedItems); 
} 

문제는 내가 라인을위한 NPE 얻고 있다는 것입니다 : 여기

@Override 
public void onLoadChatrooms(String accountId, String pageNum) { 
    getChatroomsService.getChatrooms(apiToken, createRequestBodyForGetChatroomsRequest(accountId, pageNum)) 
      .enqueue(new Callback<GetChatroomsServiceResponse>() { 
       @Override 
       public void onResponse(Call<GetChatroomsServiceResponse> call, Response<GetChatroomsServiceResponse> response) { 
        if (response.isSuccessful()) { 
         view.showData(Arrays.asList(response.body().getChatRoomsArray())); 
        } 
       } 

       @Override 
       public void onFailure(Call<GetChatroomsServiceResponse> call, Throwable t) { 

       } 
      }); 
} 

그리고는 내가 쓴 테스트입니다 chatPresenter.onLoadChatrooms(accountId, "0");

정확한 오류 메시지 :

java.lang.NullPointerException 
at my.package.main.fragments.chat.ChatPresenter.onLoadChatrooms(ChatPresenter.java:40) 
at my.package.main.fragments.chat.ChatPresenterTest.onLoadChatrooms(ChatPresenterTest.java:70) 

line 40 ChatPresenter를위한이다 : .enqueue(new Callback<GetChatroomsServiceResponse>() {

사람은 그와 함께 도와 드릴까요? Presenter가 null인지 확인하려고했는데 문제가 아닙니다.

편집 :

ChatPresenter의 생성자 :

class ChatPresenter implements ChatMVP.Presenter { 

private ChatMVP.View view; 
private GetChatroomsService getChatroomsService; 
private String apiToken; 

@Inject 
ChatPresenter(ChatMVP.View view, GetChatroomsService getChatroomsService, @Named("Api-Token") String apiToken) { 
    this.view = view; 
    this.getChatroomsService = getChatroomsService; 
    this.apiToken = apiToken; 
} 

및 GetChatroomsService :

interface GetChatroomsService { 

@POST("getchatrooms") 
Call<GetChatroomsServiceResponse> getChatrooms(@Query("api_token") String apiToken, @Body RequestBody requestBody); 

} 
+0

은'getChatroomsService' 변수이거나 괄호를 놓치셨습니까? 그리고'ChatPresenter'의 생성자는 어떻게 생겼습니까? –

+0

@TimothyTruckle ChatPresenter의 생성자 코드로 질문을 업데이트했습니다. 또한 getChatroomsService는 변수입니다 – Mes

+0

자신과 동료에게 'getChatroomsService'라는 이름을 [Java 명명 규칙] (http : //www.oracle.com/technetwork/java/codeconventions-135099.html). –

답변

1

여기서 문제가 getChatroomsService의 조롱 방법 getChatrooms()null을 반환한다는 것입니다. 가장 큰 이유는 생산 코드에 주어진 매개 변수가 모의 구성의 매개 변수와 일치하지 않기 때문입니다.

나 자신을 위해 mock을 구성 할 때 any*() 정규 표현식을 사용하고 명시 적으로 프로덕션 코드에서 전달 된 매개 변수를 확인하여 명시 적 NPE와 같은 설명이 아닌 NPE에서 나를 절약 할 수 있는지 확인하십시오.

@Test 
public void onLoadChatrooms() throws Exception { 
    when(getChatroomsService.getChatrooms(anyString(), any(RequestBody.class))) 
      .thenReturn(call); 

    chatPresenter.onLoadChatrooms(accountId, "0"); 

    verify(call).enqueue(callback.capture()); 
    callback.getValue().onResponse(call, getResponse()); 

    verify(getChatroomsService).getChatrooms(apiToken,requestBody); 
    verify(view).showData(chatroomsResponseNestedItems); 
} 
+0

와우 그게 좋은 포수 였어 !! 고마워! 나는 단위 테스트를 시작할 뿐이며'any *() '의 사용은 여전히 ​​나에게 불분명하다. 예를 들어 accountId와 pageNum vars ('onLoadChatrooms()'를 호출 할 때)에'anyString()'을 추가하기 전에 시도했지만, 지금 당장 기억할 수없는 오류가 발생했습니다. – Mes

+1

@Mes : * "와우는 좋은 포수 였어! 고마워! 내가 단위 테스트를 시작했을 뿐이야."* 처음 시작했을 때 같은 문제가 생겼다. anyString() [...]을 추가했지만 지금 당장 기억할 수없는 오류가 발생했습니다. "* Mockito는 당신이 엄격한 Matchers 또는 (모조) 객체를 사용하기를 원합니다. 매개 변수 목록에서 혼합 할 수 없습니다. –

관련 문제