在RxJava的doOnSuccess运算符中调用了单元测试验证方法
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了在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);
}
我在哪里伪造来自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);
测试按预期工作。
以上是关于在RxJava的doOnSuccess运算符中调用了单元测试验证方法的主要内容,如果未能解决你的问题,请参考以下文章