使用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(); BehaviorDelegatedelegate = mockRetrofit.create(MyService.class);
我该如何转接电话MyServiceMock
?
假设接口定义如下:
public interface MyService { @GET("/name") rx.Observablename(); }
通话将转发至MyServiceMock
使用BehaviorDelegate
.将BehaviorDelegate
适用NetworkBehavior
于由模拟产生的反应.请注意,下面的模拟实现将BehaviorDelegate
as作为构造函数参数并使用它来返回响应.
public class MyServiceMock implements MyService { private final BehaviorDelegatedelegate; public MyServiceMock(BehaviorDelegate delegate) { this.delegate = delegate; } public Observable name() { return delegate.returningResponse("test").name(); } }
使用模拟服务的测试样本如下所示:
public class MyServiceTest { private final NetworkBehavior behavior = NetworkBehavior.create(); private final rx.observers.TestSubscribertestSubscriber = 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 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); } }