2017-12-24 7 views
0

I가 내가 단위 테스트에 노력하고있어 다음 코드를단위 테스트 방법은 RxJava의 doOnSuccess 연산자 내에서 호출 된 베리 파이

if (networkUtils.isOnline()) { 
     return remoteDataSource.postComment(postId, commentText) 
       .doOnSuccess(postCommentResponse -> 
         localDataSource.postComment(postId, commentText)) 
       .subscribeOn(schedulerProvider.io()) 
       .observeOn(schedulerProvider.mainThread()); 
    } else { 
     return Single.error(new IOException()); 
    } 

그리고 나는 그것을 테스트하기 위해 노력하고있어 방법이 있습니다 :

@Test 
public void postComment_whenIsOnline_shouldCallLocalToPostComment() throws Exception { 
    // Given 
    when(networkUtils.isOnline()) 
      .thenReturn(true); 
    String postId = "100"; 
    String comment = "comment"; 

    Response<PostCommentResponse> response = postCommentResponse(); 
    when(remoteDataSource.postComment(anyString(), anyString())) 
      .thenReturn(Single.just(response)); 

    // When 
    repository.postComment(postId, comment); 

    // Then 
    verify(localDataSource).postComment(postId, comment); 
} 

어디처럼 개조에서 가짜 응답 :

private Response<PostCommentResponse> postCommentResponse() { 
    PostCommentResponse response = new PostCommentResponse(); 
    response.setError("0"); 
    response.setComment(postCommentResponseNestedItem); 

    return Response.success(response); 
} 

하지만가 결과 : Actually, there were zero interactions with this mock.

아이디어가 있으십니까?

편집 :

@RunWith(MockitoJUnitRunner.class) 
public class CommentsRepositoryTest { 

@Mock 
private CommentsLocalDataSource localDataSource; 

@Mock 
private CommentsRemoteDataSource remoteDataSource; 

@Mock 
private NetworkUtils networkUtils; 

@Mock 
private PostCommentResponseNestedItem postCommentResponseNestedItem; 

private CommentsRepository repository; 

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

    BaseSchedulerProvider schedulerProvider = new ImmediateSchedulerProvider(); 

    repository = new CommentsRepository(localDataSource, remoteDataSource, networkUtils, schedulerProvider); 
} 


    // tests 


} 
+0

'repository'는'postComment' 액션을 위임하는'remoteDataSource'에 대한 참조를 가지고 있습니까? – GVillani82

+0

예, 확실합니다. 코드가 예상대로 작동하고 있습니다 (즉, 주석을 게시하면 데이터베이스에서 찾을 수 있습니다). – mt0s

+0

예, 테스트하는 동안 데이터베이스에 영향을 미치지 않습니다. 내가 뭘 잘못한 건지 모르겠지만, 일부 또는 당신의 조롱 된 구성 요소가 주입되지 않은 것으로 판단됩니다. 'networkUtils' 또는'remoteDataSource'와 같습니다. – GVillani82

답변

0

당신이 그것을에 가입해야 Observable을 테스트 할 때 항목을 방출 시작됩니다 있도록.

내가 사용하자마자 :

TestObserver<Response<PostCommentResponse>> testObserver = new TestObserver<>(); 

및 가입에 예상대로

repository.postComment(postId, comment) 
      .subscribe(testObserver); 

는 테스트했다.

관련 문제