Robolectric 之 Jessyan Arm框架之Mvp

2019-08-09  本文已影响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

分析一波:

上篇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 会很艰难。我换了一种思维:能不能判断当前的代码在运行单元测试,跳过他呢?还有真有这种方法:
   /**
     * 是否是自动化测试中
     */
    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>
   @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空针针

  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();
    }

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

上一篇下一篇

猜你喜欢

热点阅读