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

Unit test verify method was called inside RxJava's doOnSuccess operator

我尝试对以下代码进行单元测试:

    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


}

当您想测试一个 Observable 时,您必须订阅它,这样它才会开始发射物品。

我一用就:

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

并订阅了:

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

测试按预期进行。