http://localhost:8585
我需要对这种方法进行单元测试。我正在使用Mockito。请帮我测试onSuccess()方法,因为我正在使用RxJava。
答案 0 :(得分:0)
有很多方法可以测试你的方法。但是,如果你怀疑是如何测试RxJava部分你可以使用TestSubscriber。您可以查看示例here。
你的问题是你的onCreateAccountButtonClicked方法中有很多代码,它有多个责任...所以在同一个方法中有很多测试。分别测试PasswordAndEmailValidator和creatingService是一种更好的方法。
嗯,但你想测试onSuccess吗?
你可以这样做:
TestSubscriber<RestResponse> testSubs = new TestSubscriber<>();
creationService.createUser(requestGSON).subscribe(testSubs);
testSubs.assertCompleted()
您可能需要模拟服务器。您可以使用MockWebServer
修改1:
如果你想测试类中的方法是否被调用:
1 - &gt; 当您使用RxJava时,您需要注入一个SchedulerProvider ...所以您的所有调度程序都是即时的。
像这样:
public class ImmediateSchedulerProvider {
@NonNull
@Override
public Scheduler computation() {
return Schedulers.immediate();
}
@NonNull
@Override
public Scheduler io() {
return Schedulers.immediate();
}
@NonNull
@Override
public Scheduler ui() {
return Schedulers.immediate();
}
}
然后你将这个类注入要测试的RxJava函数中。这样,您始终保持在同一个线程中,因此如果没有响应,您将无法完成测试。
好的,现在第二步。
2 - &gt; 注入您要测试的视图模拟。这是signUpView对吗?所以像这样实例化你的类:
@Mock
SighUpView sighUpView
@Before
public void setup(){
MockitoAnnotations.initMocks(this);
}
然后调用您的测试并使用方法Mokito.verify(T t)
3 - &gt;
@Test
public void someTest(){
//Inject your mock ImeddiateScheculerProvider here or elsewhere.
mSomeClass.onCreateAccountButtonClicked(mGo99ApplicationconfigureApplication, mImmediateSchudelerProvider.
//You must verify that your method was called with correct parameters!
Mockito.verify(sighUpView).login(configureApplication, createdUserObjectData.getUserId(), signUpView.getEmailAddress().toLowerCase().replaceAll("\\s", ""), signUpView.getPassword());
}
嗯,就是这样。以此为例,适应您的需求。
如果您需要更完整的实施,可以通过Google查看this repo。
快乐的编码!