当前位置:  开发笔记 > 编程语言 > 正文

如何使用Retrofit 2.0和新的MockRetrofit类来模拟服务?

如何解决《如何使用Retrofit2.0和新的MockRetrofit类来模拟服务?》经验,为你挑选了1个好方法。

使用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 delegate = mockRetrofit.create(MyService.class);

我该如何转接电话MyServiceMock



1> Praveer Gupt..:

假设接口定义如下:

public interface MyService {
    @GET("/name")
    rx.Observable name();
}

通话将转发至MyServiceMock使用BehaviorDelegate.将BehaviorDelegate适用NetworkBehavior于由模拟产生的反应.请注意,下面的模拟实现将BehaviorDelegateas作为构造函数参数并使用它来返回响应.

public class MyServiceMock implements MyService {
    private final BehaviorDelegate delegate;

    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.TestSubscriber 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 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);
    }
}

推荐阅读
惬听风吟jyy_802
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有