在RxJava的doOnSuccess运算符中调用了单元测试验证方法

时间:2017-12-24 21:31:34

标签: unit-testing mockito rx-java2

我有以下代码我正在尝试进行单元测试:

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

我伪造来自Retrofit的回复,如:

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


}

1 个答案:

答案 0 :(得分:1)

当您想要测试Observable时,您必须订阅它,以便它开始发射物品。

我一使用:

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

并订阅:

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

测试按预期工作。