如何使用Retrofit 2.0和新的MockRetrofit类模拟服务?
通过使用Retrofit 1,我们曾经模拟了Web服务并模拟了网络延迟,如下所示:
MockRestAdapter mockRestAdapter = MockRestAdapter.from(restAdapter);return mockRestAdapter.create(MyService.class, new MyServiceMock());
MyService
服务接口在哪里(将响应作为Rx Observables返回),并且MyServiceMock
是实现此接口的类。
在Retrofit
2.0.0-beta3中,有一个尚未记录的全新模拟系统(请参阅:https
:
//github.com/square/retrofit/pull/1343)。当尝试类似的东西时,我得到:
MockRetrofit mockRetrofit = new MockRetrofit.Builder(retrofit).build();BehaviorDelegate<AuthService> delegate = mockRetrofit.create(MyService.class);
如何将电话转接到MyServiceMock
?
回答:
假设接口定义如下:
public interface MyService { @GET("/name")
rx.Observable<String> name();
}
通话将被转发到MyServiceMock
使用BehaviorDelegate
。将BehaviorDelegate
适用NetworkBehavior
于由模拟产生的反应。请注意,下面的模拟实现将BehaviorDelegate
用作构造函数参数,并使用它返回响应。
public class MyServiceMock implements MyService { private final BehaviorDelegate<MyService> delegate;
public MyServiceMock(BehaviorDelegate<MyService> delegate) {
this.delegate = delegate;
}
public Observable<String> name() {
return delegate.returningResponse("test").name();
}
}
使用模拟服务的测试示例如下所示:
public class MyServiceTest { private final NetworkBehavior behavior = NetworkBehavior.create();
private final rx.observers.TestSubscriber<String> testSubscriber = TestSubscriber.create();
private MyService mockService;
@Before
public void setUp() throws Exception {
Retrofit retrofit = new Retrofit.Builder()
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.baseUrl("http://example.com").build();
MockRetrofit mockRetrofit = new MockRetrofit.Builder(retrofit)
.networkBehavior(behavior).build();
final BehaviorDelegate<MyService> delegate = mockRetrofit.create(MyService.class);
mockService = new MyServiceMock(delegate);
}
@Test
public void testSuccessResponse() throws Exception {
givenNetworkFailurePercentIs(0);
mockService.name().subscribe(testSubscriber);
testSubscriber.assertValue("test");
testSubscriber.assertCompleted();
}
@Test
public void testFailureResponse() throws Exception {
givenNetworkFailurePercentIs(100);
mockService.name().subscribe(testSubscriber);
testSubscriber.assertNoValues();
testSubscriber.assertError(IOException.class);
}
private void givenNetworkFailurePercentIs(int failurePercent) {
behavior.setDelay(0, MILLISECONDS);
behavior.setVariancePercent(0);
behavior.setFailurePercent(failurePercent);
}
}
以上是 如何使用Retrofit 2.0和新的MockRetrofit类模拟服务? 的全部内容, 来源链接: utcz.com/qa/425095.html