美文网首页
Robolectric 之 Jessyan Arm框架之Mvp

Robolectric 之 Jessyan Arm框架之Mvp

作者: DrChenZeng | 来源:发表于2019-08-09 15:09 被阅读0次

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

    分析一波:

    上篇view层的解耦,测试view 层可以近似理解为测试 LoginActivity,因为测试activity他是通过Robolectric 调用build方法创建的activity

    图片.png
    presenterModel都是真实生成的,一测试一个准儿。但是presenter是业务类,不需要生成真实的LoginActivityModel,对presenter外部的一切,我们只要通过Mockito的打桩功能(不熟悉点我)模拟假的对象返回假的方法结果,让我们专注于业务逻辑的测试!!!是不是很完美?哈哈,想象都是美好的,趟坑走起!!

    第一步上手测试

    由于上篇已经写了登录功能直接“ctrl + shift + T”测试类编写走起

    图片.png
    package me.jessyan.mvparms.demo.mvp.presenter.login;
    
    import org.junit.Assert;
    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.RobolectricTestRunner;
    import org.robolectric.annotation.Config;
    import org.robolectric.shadow.api.Shadow;
    import org.robolectric.shadows.ShadowLog;
    import org.robolectric.shadows.ShadowToast;
    import me.jessyan.mvparms.demo.BuildConfig;
     
    ···
    import static org.junit.Assert.*;
    
     
    @RunWith(RobolectricTestRunner.class)
    @Config(constants = BuildConfig.class,sdk = 27)
    public class LoginPresenterTest {
        /**
         * 引入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);
    
        }
    
        @Test
        public  void loginFailed(){
            //模拟数据,请求网络会报“密码错误”
            Mockito.when(view.getMobileStr()).thenReturn("13547250999");
            Mockito.when(view.getPassWordStr()).thenReturn("123");
            //登录
            mPresenter.login();
            //验证
            Assert.assertEquals("密码错误", ShadowToast.getTextOfLatestToast());
        }
    
        /**
         * 这是线程同步的方法
         */
        private void initRxJava() {
    ···
    }
    }
    

    这是login的业务代码,上面通过mockito模拟

    图片.png

    第一个问题:运行,空针针!?BasePresenter有问题

    图片.png
    图片.png
    一看是生命周期观察者和通信老伙计,对于单元测试没啥用,直接try{}catch 吧? 不妥!catch 是不能乱 try 的,如果以后这里代码出问题,debug 会很艰难。我换了一种思维:能不能判断当前的代码在运行单元测试,跳过他呢?还有真有这种方法:
    • 首先要理解,@RunWith(RobolectricTestRunner.class)继承了RobolectricTestRunner
      图片.png
    • 分析,所有Test继承一个base类,base再继承RobolectricTestRunner ,只要判断base类在内存中生成了,那就可以判断当前运行的是Robolectric单元测试了。
    • 继承,


      图片.png
      图片.png
    • 判断代码,路径要对哟:
       /**
         * 是否是自动化测试中
         */
        private AtomicBoolean isTestRunning;
    
        public synchronized boolean isTestRunning () {
            if (null == isTestRunning) {
                boolean istest;
    
                try {
                    //路径请更换
                    Class.forName ("me.jessyan.mvparms.demo.base.MyPresenterRunner"); // for e.g. com.example.MyTest
    
                    istest = true;
                } catch (ClassNotFoundException e) {
                    istest = false;
                }
    
                isTestRunning = new AtomicBoolean (istest);
            }
    
            return isTestRunning.get ();
        }
    
    • 报错的地方直接跳过:
     @Override
        public void onStart() {
            //将 LifecycleObserver 注册给 LifecycleOwner 后 @OnLifecycleEvent 才可以正常使用
            if (mRootView != null && mRootView instanceof LifecycleOwner ) {
                if(!isTestRunning()){
                    ((LifecycleOwner) mRootView).getLifecycle().addObserver(this);
                    if (mModel!= null && mModel instanceof LifecycleObserver){
                        ((LifecycleOwner) mRootView).getLifecycle().addObserver((LifecycleObserver) mModel);
                    }
                }
            }
            if (useEventBus()&&!isTestRunning())//如果要使用 Eventbus 请将此方法返回 true
                EventBusManager.getInstance().register(this);//注册 Eventbus
        }
    

    第二个问题:运行Model.login() 返回空针针

    图片.png
    图片.png
    debug 一下根本不会经过LoginModel类login()实现方法,原来mockito创建的类,有返回值的方法,不会经过方法就直接返回null
    图片.png
    看来只有自己实现login方法,返回正确的Observable<User>
    • mRpositoryManager 可以通过ArmsUtils.obtainAppComponentFromContext(RuntimeEnvironment.application).repositoryManager()获取那么test实现方法:
       @Test
        public  void loginFailed(){
            //模拟数据,请求网络会报“密码错误”
            Mockito.when(view.getMobileStr()).thenReturn("13547250999");
            Mockito.when(view.getPassWordStr()).thenReturn("123");
    
            //实现loginModel login 方法
            //由于不知道上哪里去找一个稳定且长期可用的登录接口,
            // 所以用的接口是github 上的查询接口:https://api.github.com/users/drchengit
            // 这里的处理是正确的密码,请求存在的用户名:drchengit  错误的密码请求不存在的用户名: drchengi
            Observable<User> observable = ArmsUtils.obtainAppComponentFromContext(
                    RuntimeEnvironment.application).repositoryManager()
                    .obtainRetrofitService(CommonService.class)
                    .getUser("drchengi");
    
            //模拟无论怎么调用,login都是返回上面的Observable对象
            Mockito.when(model.login(Mockito.anyString(),Mockito.anyString()))
                    .thenReturn(observable);
            //登录
            mPresenter.login();
            //验证
            Assert.assertEquals("密码错误", ShadowToast.getTextOfLatestToast());
        }
    

    运行

    第三个问题RxLifecycleUtils空针针

    • RxLifecycleUtils 类bindToLifecycle方法报空,但是这里却不能try catch 和逃过返回null 值,因为返回null給外面,一样是没有解决问题,如果外面调用地方多的话,改动工程量会很大,每一个地方都要try或者跳过,这里必须解决在内部
      图片.png
      图片.png
      新建一个假的生命周期
      图片.png
      改造后的代码
      public static <T> LifecycleTransformer<T> bindToLifecycle(@NonNull Lifecycleable lifecycleable) {
    
            try {
                Preconditions.checkNotNull(lifecycleable, "lifecycleable == null");
                if (lifecycleable instanceof ActivityLifecycleable) {
                    return RxLifecycleAndroid.bindActivity(((ActivityLifecycleable) lifecycleable).provideLifecycleSubject());
                } else if (lifecycleable instanceof FragmentLifecycleable) {
                    return RxLifecycleAndroid.bindFragment(((FragmentLifecycleable) lifecycleable).provideLifecycleSubject());
                } else {
                    throw new IllegalArgumentException("Lifecycleable not match");
                }
            }catch (NullPointerException e){
                if(isTesting()){//这个方法判断是否正在 robolectric 单元测试
                    return RxLifecycleAndroid.bindActivity(new TestLife().provideLifecycleSubject());
                }else {
                    throw e;
                }
            }
    
        }
    

    运行,空针针

    第四个问题mErroHandler 空针针

    图片.png
    由于单元测试只是简单加载了,很多东西并没有初始化,就包括mErroHandler
    图片.png
    • 于是我自己在测试类中现造一个:
       @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();
        }
    
    • 运行一路绿灯,这里框架的解耦Presenter层的测试就完成了

    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,一个温润的男子,版权所有,未经允许不得抄袭。

    相关文章

      网友评论

          本文标题:Robolectric 之 Jessyan Arm框架之Mvp

          本文链接:https://www.haomeiwen.com/subject/mxdcjctx.html