Robolectric 實(shí)戰(zhàn)解耦整個(gè)系列:
Robolectric 之 Jessyan Arm框架之Mvp 單元測試解耦過程(View 層)
Robolectric 之 Jessyan Arm框架之Mvp 單元測試解耦過程(Presenter 層)
Robolectric 之 Jessyan Arm框架之Mvp 單元測試本地json測試
github的鏈接: https://github.com/drchengit/Robolectric_arm_mvp
分析:
本地json 測試顧名思義一開始就編好了網(wǎng)絡(luò)請求的返回結(jié)果的json數(shù)據(jù),每次發(fā)起請求無論是成功不成功,都會(huì)馬上返回本地寫好的結(jié)果。原理:利用okHttp的的插值器,攔截?cái)?shù)據(jù)并模擬。
第一步新建測試類
- ctrl + shift + T
package me.jessyan.mvparms.demo.mvp.presenter.login;
import com.jess.arms.utils.ArmsUtils;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule;
import org.robolectric.RuntimeEnvironment;
import org.robolectric.annotation.Config;
import org.robolectric.shadows.ShadowLog;
import io.reactivex.Observable;
import io.reactivex.Scheduler;
import io.reactivex.android.plugins.RxAndroidPlugins;
import io.reactivex.functions.Function;
import io.reactivex.plugins.RxJavaPlugins;
import io.reactivex.schedulers.Schedulers;
import me.jessyan.mvparms.demo.BuildConfig;
import me.jessyan.mvparms.demo.app.ResponseErrorListenerImpl;
/**
* @author DrChen
* @Date 2019/8/9 0009.
* qq:1414355045
* 這個(gè)類是本地json請求
*/
@RunWith(MyPresenterRunner.class)
@Config(constants = BuildConfig.class, sdk = 27)
public class LoginPresenterTestMock {
/**
* 引入mockito 模擬假數(shù)據(jù)
*/
@Rule
public MockitoRule mockitoRule = MockitoJUnit.rule();
private LoginPresenter mPresenter;
private LoginModel model;
private LoginContract.View view;
@Before
public void setUp() throws Exception {
//打印log
ShadowLog.stream = System.out;
//線程同步走起
initRxJava();
//模擬假對象
model = Mockito.mock(LoginModel.class);
view = Mockito.mock(LoginActivity.class);//這里生命周期不會(huì)調(diào)用,只是一個(gè)簡單java 對象
mPresenter = new LoginPresenter(model, view);
mPresenter.mErrorHandler = RxErrorHandler
.builder()
.with(RuntimeEnvironment.application)
.responseErrorListener(new ResponseErrorListenerImpl())
.build();
}
/**
* 這是線程同步的方法
*/
private void initRxJava() {
RxJavaPlugins.reset();
RxJavaPlugins.setIoSchedulerHandler(new Function<Scheduler, Scheduler>() {
@Override
public Scheduler apply(Scheduler scheduler) throws Exception {
return Schedulers.trampoline();
}
});
//這個(gè)喲
RxJavaPlugins.setSingleSchedulerHandler(new Function<Scheduler, Scheduler>() {
@Override
public Scheduler apply(Scheduler scheduler) throws Exception {
return Schedulers.trampoline();
}
});
RxAndroidPlugins.reset();
RxAndroidPlugins.setMainThreadSchedulerHandler(new Function<Scheduler, Scheduler>() {
@Override
public Scheduler apply(Scheduler scheduler) throws Exception {
return Schedulers.trampoline();
}
});
}
//登錄測試
@Test
public void loginFailed() {
//模擬數(shù)據(jù)
Mockito.when(view.getMobileStr()).thenReturn("13547250999");
Mockito.when(view.getPassWordStr()).thenReturn("abc");
//登錄
mPresenter.login();
//驗(yàn)證
Assert.assertEquals("密碼錯(cuò)誤", ShadowToast.getTextOfLatestToast());
}
}
運(yùn)行會(huì)報(bào)空針針,是上篇presenter解耦時(shí)提到過,LoginModel.login()會(huì)返回一個(gè)空對象,可以利用mockito打樁,模擬返回值。
第二步新建網(wǎng)絡(luò)請求相關(guān)文件
-
新建一個(gè)OkHttp 插值器: MockInterceptor 負(fù)責(zé)攔截加載假數(shù)據(jù)
要建四個(gè)文件:
圖片.png
package me.jessyan.mvparms.demo.net;
import java.io.IOException;
import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Protocol;
import okhttp3.Response;
import okhttp3.ResponseBody;
/**
* 網(wǎng)絡(luò)請求的攔截器,用于Mock響應(yīng)數(shù)據(jù)
* 參考文章:
* http://stackoverflow.com/questions/17544751/square-retrofit-server-mock-for-testing
* https://github.com/square/okhttp/wiki/Interceptors
*/
public class MockInterceptor implements Interceptor {
private final String responeJsonPath;
public MockInterceptor(String responeJsonPath) {
this.responeJsonPath = responeJsonPath;
}
@Override
public Response intercept(Chain chain) throws IOException {
String responseString = createResponseBody(chain);
Response response = new Response.Builder()
.code(200)
.message("ok")
.request(chain.request())
.protocol(Protocol.HTTP_1_0)
.body(ResponseBody.create(MediaType.parse("application/json"), responseString.getBytes()))
.addHeader("content-type", "application/json")
.build();
Log.e("結(jié)果",responseString);
return response;
}
/**
* 讀文件獲取json字符串,生成ResponseBody
*
* @param chain
* @return
*/
private String createResponseBody(Chain chain) {
String responseString = null;
HttpUrl uri = chain.request().url();
String path = uri.url().getPath();
if (path.matches("^(/users/)+[^/]*+$")) {//匹配/users/{username}
responseString = getResponseString("users.json");
}
return responseString;
}
private String getResponseString(String fileName) {
return FileUtil.readFile(responeJsonPath + fileName, "UTF-8").toString();
}
}
- 新建json文件(這個(gè)要提示密碼錯(cuò)誤):user.json
{
"message": "Not Found",
"documentation_url": "https://developer.github.com/v3/users/#get-a-single-user"
}
- 新建一個(gè)的TestRetrofit負(fù)責(zé)構(gòu)建Retrofit 和 OkHttp :
package me.jessyan.mvparms.demo.net;
/**
* @author DrChen
* @Date 2019/8/7 0007.
* qq:1414355045
*/
public class TestRetrofit<T> {
/**
*
* 本地?cái)?shù)據(jù)模擬
*/
public T createMockService(Class<T> service,String json) {
OkHttpClient okHttpClient = new OkHttpClient.Builder()
.connectTimeout(1, TimeUnit.SECONDS)//一秒超時(shí)
.readTimeout(1, TimeUnit.SECONDS)//一秒超時(shí),快速結(jié)束請求
.addInterceptor(new MockInterceptor(json))//最后得到假數(shù)據(jù)
.build();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(Api.APP_DOMAIN)
.client(okHttpClient)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build();
return retrofit.create(service);
}
}
這時(shí)會(huì)提示報(bào)錯(cuò)
gradle加入這兩個(gè)依賴
//Retrofit test
testImplementation "com.squareup.retrofit2:converter-gson:2.4.0"
testImplementation ("com.squareup.retrofit2:adapter-rxjava2:2.4.0"){
exclude module: 'rxjava'
}
- 新建FileUtils類
package me.jessyan.mvparms.demo.net;
public class FileUtil {
public static StringBuilder readFile(String filePath, String charsetName) {
File file = new File(filePath);
StringBuilder fileContent = new StringBuilder("");
if (file == null || !file.isFile()) {
return null;
}
BufferedReader reader = null;
try {
InputStreamReader is = new InputStreamReader(new FileInputStream(file), charsetName);
reader = new BufferedReader(is);
String line = null;
while ((line = reader.readLine()) != null) {
fileContent.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return fileContent;
}
}
- 修改測試類中的代碼
package me.jessyan.mvparms.demo.mvp.presenter.login;
···
@RunWith(MyPresenterRunner.class)
@Config(constants = BuildConfig.class, sdk = 27)
public class LoginPresenterTestMock {
···
String dirPath;
@Before
public void setUp() throws Exception {
···
dirPath = getClass().getResource("/json/").toURI().getPath();//得到j(luò)son文件夾位置
}
···
@Test
public void loginFailed() {
//模擬數(shù)據(jù)
Mockito.when(view.getMobileStr()).thenReturn("13547250999");
Mockito.when(view.getPassWordStr()).thenReturn("abc");
//實(shí)現(xiàn)loginModel login 方法
//由于不知道上哪里去找一個(gè)穩(wěn)定且長期可用的登錄接口,
// 所以用的接口是github 上的查詢接口:https://api.github.com/users/drchengit
// 這里的處理是正確的密碼,請求存在的用戶名:drchengit 錯(cuò)誤的密碼請求不存在的用戶名: drchengi
Observable<User> observable = new TestRetrofit<CommonService>().createMockService(CommonService.class,dirPath)
.getUser("drchengit");
//模擬無論怎么調(diào)用,login都是返回上面的Observable對象
Mockito.when(model.login(Mockito.anyString(), Mockito.anyString()))
.thenReturn(observable);
//登錄
mPresenter.login();
//驗(yàn)證
Assert.assertEquals("密碼錯(cuò)誤", ShadowToast.getTextOfLatestToast());
}
}
-
運(yùn)行,結(jié)果返回正確,但是沒有打印登錄失敗的toast
(我在網(wǎng)絡(luò)框架代碼里面寫了一些邏輯,如果message 是“Not Found” 會(huì)拋出異常,并打印Toast"密碼錯(cuò)誤")
圖片.png
TestRetrofit類中只是一個(gè)新建的Retrofit + OkHttp 的框架,只有一 個(gè)MockInterceptor插值器,想要真實(shí)復(fù)制項(xiàng)目的完整網(wǎng)絡(luò)請求情況,還得花些功夫
第三步了解Arm網(wǎng)絡(luò)框架邏輯
想要復(fù)制真實(shí)網(wǎng)絡(luò)框架邏輯首先要了解網(wǎng)框架邏輯:
jessyan 的arm 框架 初始化大量采用的dagger2,這個(gè)框架很好,但是解耦時(shí)總是看得人云里霧里。講的不好請見諒!點(diǎn)我去jessyan的博客
-
GlobalConfiguration
applyOptions這個(gè)方法在加載BaseApplication 時(shí),被代理類AppDelegate調(diào)用,新建并傳遞了一個(gè)GlobalConfigModule.Builder,提供給外部配置。
public final class GlobalConfiguration implements ConfigModule {
@Override
public void applyOptions(Context context, GlobalConfigModule.Builder builder) {
if (!BuildConfig.LOG_DEBUG) { //Release 時(shí),讓框架不再打印 Http 請求和響應(yīng)的信息
builder.printHttpLogLevel(RequestInterceptor.Level.NONE);
}
builder.baseurl(Api.APP_DOMAIN)
//強(qiáng)烈建議自己自定義圖片加載邏輯, 因?yàn)?arms-imageloader-glide 提供的 GlideImageLoaderStrategy 并不能滿足復(fù)雜的需求
//請參考 https://github.com/JessYanCoding/MVPArms/wiki#3.4
.imageLoaderStrategy(new GlideImageLoaderStrategy())
// 這里提供一個(gè)全局處理 Http 請求和響應(yīng)結(jié)果的處理類,可以比客戶端提前一步拿到服務(wù)器返回的結(jié)果,可以做一些操作,比如token超時(shí),重新獲取
.globalHttpHandler(new GlobalHttpHandlerImpl(context))
// 用來處理 rxjava 中發(fā)生的所有錯(cuò)誤,rxjava 中發(fā)生的每個(gè)錯(cuò)誤都會(huì)回調(diào)此接口
// rxjava必要要使用ErrorHandleSubscriber(默認(rèn)實(shí)現(xiàn)Subscriber的onError方法),此監(jiān)聽才生效
.responseErrorListener(new ResponseErrorListenerImpl())
.gsonConfiguration((context1, gsonBuilder) -> {//這里可以自己自定義配置Gson的參數(shù)
gsonBuilder
.serializeNulls()//支持序列化null的參數(shù)
.enableComplexMapKeySerialization();//支持將序列化key為object的map,默認(rèn)只能序列化key為string的map
})
.retrofitConfiguration((context1, retrofitBuilder) -> {//這里可以自己自定義配置Retrofit的參數(shù), 甚至您可以替換框架配置好的 OkHttpClient 對象 (但是不建議這樣做, 這樣做您將損失框架提供的很多功能)
// retrofitBuilder.addConverterFactory(FastJsonConverterFactory.create());//比如使用fastjson替代gson
});
```
}
···
}
-
GlobalConfigModule.Builder
他是一個(gè)構(gòu)建器,為GlobalConfigModule 提供對象, -
GlobalConfigModule
他是個(gè)爺爺,為全局提供使用者外部定義的一些參數(shù),比如自定義的插值器、緩存策略、BaseUrl 等..
圖片.png -
ClientModule
他是實(shí)際創(chuàng)建Retrofit 和OkHttp的類:
GlobalConfigModule在GlobalConfiguration 類的applyOptions() 方法中被使用者自定義了一些構(gòu)建了網(wǎng)絡(luò)框架的參數(shù),提供給ClientModule這個(gè)類,讓他新建Retrofit 和OkHttp的對象。
@Module
public abstract class ClientModule {
···
@Singleton
@Provides
static Retrofit provideRetrofit(Application application, @Nullable RetrofitConfiguration configuration, Retrofit.Builder builder, OkHttpClient client
, HttpUrl httpUrl, Gson gson) {
builder
.baseUrl(httpUrl)//域名
.client(client);//設(shè)置okhttp
if (configuration != null)
configuration.configRetrofit(application, builder);
builder
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())//使用 Rxjava
.addConverterFactory(GsonConverterFactory.create(gson));//使用 Gson
return builder.build();
}
@Singleton
@Provides
static OkHttpClient provideClient(Application application, @Nullable OkhttpConfiguration configuration, OkHttpClient.Builder builder, Interceptor intercept
, @Nullable List<Interceptor> interceptors, @Nullable GlobalHttpHandler handler, ExecutorService executorService) {
builder
.connectTimeout(TIME_OUT, TimeUnit.SECONDS)
.readTimeout(TIME_OUT, TimeUnit.SECONDS)
.addNetworkInterceptor(intercept);
if (handler != null)
builder.addInterceptor(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
return chain.proceed(handler.onHttpRequestBefore(chain, chain.request()));
}
});
if (interceptors != null) {//如果外部提供了interceptor的集合則遍歷添加
for (Interceptor interceptor : interceptors) {
builder.addInterceptor(interceptor);
}
}
// 為 OkHttp 設(shè)置默認(rèn)的線程池。
builder.dispatcher(new Dispatcher(executorService));
if (configuration != null)
configuration.configOkhttp(application, builder);
return builder.build();
}
···
}
-
畫個(gè)圖吧
提供類.png
第四步完全復(fù)制真實(shí)網(wǎng)絡(luò)框架
-
看看OkHttpClient 的設(shè)置:ClientMoudle類中,新建OkHttpClient有四個(gè)需要注意的參數(shù)
image.png -
第一個(gè)配置在ClientMoudle類中找到這個(gè)。
@bind 參數(shù)是實(shí)例化RequestInterceptor 直接返回
, -
第二個(gè)參數(shù)是實(shí)現(xiàn)的插值器,主要找到handler對象,在GlobalConfiguration中給了GlobalconfigMoudle再提供給ClientMoudle:
image.png - 第三個(gè)參數(shù)GlobalConfiguration沒有提供,GlobalConfigMoudle沒有被調(diào)用。
- 第四個(gè)線程池可有可無,還是加上吧!在GlobalConfigMoudule中:
/**
* 返回一個(gè)全局公用的線程池,適用于大多數(shù)異步需求。
* 避免多個(gè)線程池創(chuàng)建帶來的資源消耗。
*
* @return {@link Executor}
*/
@Singleton
@Provides
ExecutorService provideExecutorService() {
return mExecutorService == null ? new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>(), Util.threadFactory("Arms Executor", false)) : mExecutorService;
}
- 終上所述,復(fù)制真實(shí)的框架的代碼:
/**
*
* 本地?cái)?shù)據(jù)模擬
*/
public T createMockService(Class<T> service,String json) {
//打log 的神器
RequestInterceptor interceptor = new RequestInterceptor();
GlobalHttpHandler mHandler = new GlobalHttpHandlerImpl(RuntimeEnvironment.application);
OkHttpClient okHttpClient = new OkHttpClient.Builder()
.connectTimeout(1, TimeUnit.SECONDS)//一秒超時(shí)
.readTimeout(1, TimeUnit.SECONDS)//一秒超時(shí),快速結(jié)束請求
.addInterceptor(new Interceptor() {//真實(shí)的,全局錯(cuò)誤
@Override
public Response intercept(Interceptor.Chain chain) throws IOException {
return chain.proceed( mHandler.onHttpRequestBefore(chain, chain.request()));
}
})
.addInterceptor(interceptor)
.addInterceptor(new MockInterceptor(json))//最后得到假數(shù)據(jù)
// 為 OkHttp 設(shè)置默認(rèn)的線程池。
.dispatcher(new Dispatcher(new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>(), Util.threadFactory("Arms Executor", false)) ))
.build();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(Api.APP_DOMAIN)
.client(okHttpClient)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build();
return retrofit.create(service);
}
測試代碼,運(yùn)行
@Test
public void loginFailed() {
//模擬數(shù)據(jù)
Mockito.when(view.getMobileStr()).thenReturn("13547250999");
Mockito.when(view.getPassWordStr()).thenReturn("sss");
//實(shí)現(xiàn)loginModel login 方法
//由于不知道上哪里去找一個(gè)穩(wěn)定且長期可用的登錄接口,
// 所以用的接口是github 上的查詢接口:https://api.github.com/users/drchengit
// 這里的處理是正確的密碼,請求存在的用戶名:drchengit 錯(cuò)誤的密碼請求不存在的用戶名: drchengi
Observable<User> observable = new TestRetrofit<CommonService>().createMockService(CommonService.class,dirPath)
.getUser("drchengi");
//模擬無論怎么調(diào)用,login都是返回上面的Observable對象
Mockito.when(model.login(Mockito.anyString(), Mockito.anyString()))
.thenReturn(observable);
//登錄
mPresenter.login();
//驗(yàn)證
Assert.assertEquals("密碼錯(cuò)誤", ShadowToast.getTextOfLatestToast());
}
請求錯(cuò)誤,還是沒有調(diào)用,框架錯(cuò)誤的處理邏輯:
**debug一下,發(fā)現(xiàn)RequestInterceptor 類,中執(zhí)行回調(diào)的handler 為空,當(dāng)然不會(huì)執(zhí)行錯(cuò)誤處理邏輯:
又是@inject 的對象為空,空的對象還得自己建,修改TestRetrofit的代碼:
(爆紅的地方,讓他的feild為public 可以訪問)
/**
*
* 本地?cái)?shù)據(jù)模擬
*/
public T createMockService(Class<T> service,String json) {
//打log 的神器
RequestInterceptor interceptor = new RequestInterceptor();
interceptor.printLevel = RequestInterceptor.Level.ALL;
interceptor.mPrinter = new DefaultFormatPrinter();
interceptor.mHandler = new GlobalHttpHandlerImpl(RuntimeEnvironment.application);
OkHttpClient okHttpClient = new OkHttpClient.Builder()
.connectTimeout(1, TimeUnit.SECONDS)//一秒超時(shí)
.readTimeout(1, TimeUnit.SECONDS)//一秒超時(shí),快速結(jié)束請求
.addInterceptor(new Interceptor() {//真實(shí)的,全局錯(cuò)誤
@Override
public Response intercept(Interceptor.Chain chain) throws IOException {
return chain.proceed(interceptor.mHandler.onHttpRequestBefore(chain, chain.request()));
}
})
.addInterceptor(interceptor)
.addInterceptor(new MockInterceptor(json))//最后得到假數(shù)據(jù)
// 為 OkHttp 設(shè)置默認(rèn)的線程池。
.dispatcher(new Dispatcher(new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>(), Util.threadFactory("Arms Executor", false)) ))
.build();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(Api.APP_DOMAIN)
.client(okHttpClient)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build();
return retrofit.create(service);
}
運(yùn)行,ok,正常toast ,正常的log
到這里jessyan 的arm Robolectirc 本地?cái)?shù)據(jù)進(jìn)行網(wǎng)絡(luò)測試完成
Robolectric 實(shí)戰(zhàn)解耦整個(gè)系列:
Robolectric 之 Jessyan Arm框架之Mvp 單元測試解耦過程(View 層)
Robolectric 之 Jessyan Arm框架之Mvp 單元測試解耦過程(Presenter 層)
Robolectric 之 Jessyan Arm框架之Mvp 單元測試本地json測試
github的鏈接: https://github.com/drchengit/Robolectric_arm_mvp
測試資源放送
我是drchen,一個(gè)溫潤的男子,版權(quán)所有,未經(jīng)允許不得抄襲。