Unit testing 单元测试验证方法在RxJava';s-doOnSuccess算子
我尝试对以下代码进行单元测试:Unit testing 单元测试验证方法在RxJava';s-doOnSuccess算子,unit-testing,mockito,rx-java2,Unit Testing,Mockito,Rx Java2,我尝试对以下代码进行单元测试: if (networkUtils.isOnline()) { return remoteDataSource.postComment(postId, commentText) .doOnSuccess(postCommentResponse -> localDataSource.postComment(postId, commentText))
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);
}
当你想测试一个
可观察的时,你必须订阅它,这样它就会开始发射项目
我一使用:
TestObserver<Response<PostCommentResponse>> testObserver = new TestObserver<>();
测试按预期进行。您确定您的存储库
有一个远程数据源
的引用,该引用正在将后命令
操作委派给它吗?是的,我确定。代码按预期工作(这意味着当我发布注释时,我可以在数据库中找到它)是的,但我不希望在测试时数据库受到影响。我不知道出了什么问题,但我怀疑某些或您的模拟组件没有被注入。像networkUtils
或remoteDataSource
@GVillani82,我用测试类中的一些代码编辑了这个问题,以防它有所帮助。
@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
}
TestObserver<Response<PostCommentResponse>> testObserver = new TestObserver<>();
repository.postComment(postId, comment)
.subscribe(testObserver);