wuhenzhizao / android-mockserver

mock http request(retrofit + okhttp) for unit test,单元测试中模拟接口请求数据
16 stars 2 forks source link

请问这个mockserver怎么运行 #1

Open taixiang opened 6 years ago

taixiang commented 6 years ago

你好,请问这个mockserver怎么运行的,有没有demo或者文档之类的,谢谢

wuhenzhizao commented 6 years ago

在单元测试中,异步网络请求不是很好测试,mockserver提供了一个retrofit + okhttp的网络请求模拟。ApiManager类封装了retrofit,负责真实网络请求的发送; OkHttpClientStub,用本地数据模拟retrofit远程请求; BaseUseCaseTest中, private void initMockServer() { clientStub = new OkHttpClientStub();

    String baseUrl = "https://localhost:80";
    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(baseUrl)
            .addConverterFactory(GsonConverterFactory.create(new Gson()))
            .client(clientStub)
            .build();

    Whitebox.setInternalState(ApiManager.instance(), "retrofit", retrofit);

} 通过powermock,使用反射,用本地server接管远程服务。

使用步骤: 1、继承BaseUseCaseTest这个类,或者将里面的代码搬到自己的单元测试基类里 2、调用BaseUseCaseTest中如下方法设置网络返回数据: protected void mockServerRequest(String path, int code, String body) throws Exception { ResponseBody responseBody = ResponseBody.create(MediaType.parse("application/json"), body); Response.Builder mockBuilder = new Response.Builder() .protocol(Protocol.HTTP_1_1) .code(code) .body(responseBody);

    clientStub.mockResponse(path, mockBuilder);

} path是url,比如接口请求是https://www.baidu.com/map/xxx,path指map/xxx,https://www.baidu.com / 是baseUrl,在ApiManager初始化的时候赋值 code是模拟接口返回code body是接口返回数据