Robolectric 之 Jessyan Arm框架之Mvp

2019-08-12  本文已影响0人  DrChenZeng

Robolectric 实战解耦整个系列:
Robolectric 之 Jessyan Arm框架之Mvp 单元测试解耦过程(View 层)
Robolectric 之 Jessyan Arm框架之Mvp 单元测试解耦过程(Presenter 层)
Robolectric 之 Jessyan Arm框架之Mvp 单元测试本地json测试
github的链接: https://github.com/drchengit/Robolectric_arm_mvp

分析:
本地json 测试顾名思义一开始就编好了网络请求的返回结果的json数据,每次发起请求无论是成功不成功,都会马上返回本地写好的结果。原理:利用okHttp的的插值器,拦截数据并模拟。

第一步新建测试类

图片.png
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
 * 这个类是本地json请求
 */
@RunWith(MyPresenterRunner.class)
@Config(constants = BuildConfig.class, sdk = 27)
public class LoginPresenterTestMock {
    /**
     * 引入mockito 模拟假数据
     */
    @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);//这里生命周期不会调用,只是一个简单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();
            }
        });

        //这个哟
        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() {
        //模拟数据
        Mockito.when(view.getMobileStr()).thenReturn("13547250999");
        Mockito.when(view.getPassWordStr()).thenReturn("abc");
        //登录
        mPresenter.login();
        //验证
        Assert.assertEquals("密码错误", ShadowToast.getTextOfLatestToast());

   }
}

运行会报空针针,是上篇presenter解耦时提到过,LoginModel.login()会返回一个空对象,可以利用mockito打桩,模拟返回值。

第二步新建网络请求相关文件

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;

/**
 * 网络请求的拦截器,用于Mock响应数据
 * 参考文章:
 * 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("结果",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();
    }

}

{
    "message": "Not Found",
    "documentation_url": "https://developer.github.com/v3/users/#get-a-single-user"
}
package me.jessyan.mvparms.demo.net;
 

/**
 * @author DrChen
 * @Date 2019/8/7 0007.
 * qq:1414355045
 */
public class TestRetrofit<T> {
    /**
     *
    *   本地数据模拟
     */
    public T createMockService(Class<T> service,String json) {
        OkHttpClient okHttpClient =  new OkHttpClient.Builder()
                .connectTimeout(1, TimeUnit.SECONDS)//一秒超时
                .readTimeout(1, TimeUnit.SECONDS)//一秒超时,快速结束请求
                 .addInterceptor(new MockInterceptor(json))//最后得到假数据
                               .build();
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(Api.APP_DOMAIN)
                .client(okHttpClient)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build();
        return retrofit.create(service);
    }



}

这时会提示报错

图片.png

gradle加入这两个依赖

   //Retrofit test
    testImplementation   "com.squareup.retrofit2:converter-gson:2.4.0"
    testImplementation ("com.squareup.retrofit2:adapter-rxjava2:2.4.0"){
        exclude module: 'rxjava'
    }
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();//得到json文件夹位置
    }

 ···
    @Test
    public void loginFailed() {
        //模拟数据
        Mockito.when(view.getMobileStr()).thenReturn("13547250999");
        Mockito.when(view.getPassWordStr()).thenReturn("abc");

      
        //实现loginModel login 方法
        //由于不知道上哪里去找一个稳定且长期可用的登录接口,
        // 所以用的接口是github 上的查询接口:https://api.github.com/users/drchengit
        // 这里的处理是正确的密码,请求存在的用户名:drchengit  错误的密码请求不存在的用户名: drchengi
        Observable<User> observable =  new TestRetrofit<CommonService>().createMockService(CommonService.class,dirPath)
                .getUser("drchengit");

        //模拟无论怎么调用,login都是返回上面的Observable对象
        Mockito.when(model.login(Mockito.anyString(), Mockito.anyString()))
                .thenReturn(observable);
        //登录
        mPresenter.login();
        //验证
        Assert.assertEquals("密码错误", ShadowToast.getTextOfLatestToast());
      
    }
}

第三步了解Arm网络框架逻辑

想要复制真实网络框架逻辑首先要了解网框架逻辑:
jessyan 的arm 框架 初始化大量采用的dagger2,这个框架很好,但是解耦时总是看得人云里雾里。讲的不好请见谅!点我去jessyan的博客


public final class GlobalConfiguration implements ConfigModule {
 
  
    @Override
    public void applyOptions(Context context, GlobalConfigModule.Builder builder) {
        if (!BuildConfig.LOG_DEBUG) { //Release 时,让框架不再打印 Http 请求和响应的信息
            builder.printHttpLogLevel(RequestInterceptor.Level.NONE);
        }

        builder.baseurl(Api.APP_DOMAIN)
                //强烈建议自己自定义图片加载逻辑, 因为 arms-imageloader-glide 提供的 GlideImageLoaderStrategy 并不能满足复杂的需求
                //请参考 https://github.com/JessYanCoding/MVPArms/wiki#3.4
                .imageLoaderStrategy(new GlideImageLoaderStrategy())
 

              // 这里提供一个全局处理 Http 请求和响应结果的处理类,可以比客户端提前一步拿到服务器返回的结果,可以做一些操作,比如token超时,重新获取
                .globalHttpHandler(new GlobalHttpHandlerImpl(context))
                // 用来处理 rxjava 中发生的所有错误,rxjava 中发生的每个错误都会回调此接口
                // rxjava必要要使用ErrorHandleSubscriber(默认实现Subscriber的onError方法),此监听才生效
                .responseErrorListener(new ResponseErrorListenerImpl())
                .gsonConfiguration((context1, gsonBuilder) -> {//这里可以自己自定义配置Gson的参数
                    gsonBuilder
                            .serializeNulls()//支持序列化null的参数
                            .enableComplexMapKeySerialization();//支持将序列化key为object的map,默认只能序列化key为string的map
                })
                .retrofitConfiguration((context1, retrofitBuilder) -> {//这里可以自己自定义配置Retrofit的参数, 甚至您可以替换框架配置好的 OkHttpClient 对象 (但是不建议这样做, 这样做您将损失框架提供的很多功能)
//                    retrofitBuilder.addConverterFactory(FastJsonConverterFactory.create());//比如使用fastjson替代gson
                });

       ```
    }

 ···

}

@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);//设置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 设置默认的线程池。
        builder.dispatcher(new Dispatcher(executorService));

        if (configuration != null)
            configuration.configOkhttp(application, builder);
        return builder.build();
    }
···
}

第四步完全复制真实网络框架

image.png
    /**
     * 返回一个全局公用的线程池,适用于大多数异步需求。
     * 避免多个线程池创建带来的资源消耗。
     *
     * @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;
    }
    /**
     *
    *   本地数据模拟
     */
    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)//一秒超时
                .readTimeout(1, TimeUnit.SECONDS)//一秒超时,快速结束请求
                .addInterceptor(new Interceptor() {//真实的,全局错误
                    @Override
                    public Response intercept(Interceptor.Chain chain) throws IOException {
                        return chain.proceed( mHandler.onHttpRequestBefore(chain, chain.request()));
                    }
                })
                .addInterceptor(interceptor)
                 .addInterceptor(new MockInterceptor(json))//最后得到假数据
                //                 为 OkHttp 设置默认的线程池。
                .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);
    }

测试代码,运行

 @Test
    public void loginFailed() {
        //模拟数据
        Mockito.when(view.getMobileStr()).thenReturn("13547250999");
        Mockito.when(view.getPassWordStr()).thenReturn("sss");


        //实现loginModel login 方法
        //由于不知道上哪里去找一个稳定且长期可用的登录接口,
        // 所以用的接口是github 上的查询接口:https://api.github.com/users/drchengit
        // 这里的处理是正确的密码,请求存在的用户名:drchengit  错误的密码请求不存在的用户名: drchengi
        Observable<User> observable =  new TestRetrofit<CommonService>().createMockService(CommonService.class,dirPath)
                .getUser("drchengi");

        //模拟无论怎么调用,login都是返回上面的Observable对象
        Mockito.when(model.login(Mockito.anyString(), Mockito.anyString()))
                .thenReturn(observable);
        //登录
        mPresenter.login();
        //验证
        Assert.assertEquals("密码错误", ShadowToast.getTextOfLatestToast());

    }

请求错误,还是没有调用,框架错误的处理逻辑:

image.png
**debug一下,发现RequestInterceptor 类,中执行回调的handler 为空,当然不会执行错误处理逻辑:
image.png
又是@inject 的对象为空,空的对象还得自己建,修改TestRetrofit的代码:(爆红的地方,让他的feild为public 可以访问)
    /**
     *
    *   本地数据模拟
     */
    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)//一秒超时
                .readTimeout(1, TimeUnit.SECONDS)//一秒超时,快速结束请求
                .addInterceptor(new Interceptor() {//真实的,全局错误
                    @Override
                    public Response intercept(Interceptor.Chain chain) throws IOException {
                        return chain.proceed(interceptor.mHandler.onHttpRequestBefore(chain, chain.request()));
                    }
                })
                .addInterceptor(interceptor)
                 .addInterceptor(new MockInterceptor(json))//最后得到假数据
                //                 为 OkHttp 设置默认的线程池。
                .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);
    }

运行,ok,正常toast ,正常的log

image.png

到这里jessyan 的arm Robolectirc 本地数据进行网络测试完成

Robolectric 实战解耦整个系列:
Robolectric 之 Jessyan Arm框架之Mvp 单元测试解耦过程(View 层)
Robolectric 之 Jessyan Arm框架之Mvp 单元测试解耦过程(Presenter 层)
Robolectric 之 Jessyan Arm框架之Mvp 单元测试本地json测试
github的链接: https://github.com/drchengit/Robolectric_arm_mvp
测试资源放送

我是drchen,一个温润的男子,版权所有,未经允许不得抄袭。

上一篇下一篇

猜你喜欢

热点阅读