单元测试--Robolectric及代码覆盖率

转载请注明出处:单元测试--Robolectric及代码覆盖率_robolectric覆盖率_Mr_Leixiansheng的博客-CSDN博客

步骤:

1、添加依赖 

    testCompile "org.robolectric:robolectric:3.0"
    //assertj 依赖
    testCompile 'org.assertj:assertj-core:1.7.1'
    //测试Fragment需要添加的依赖
    testCompile "org.robolectric:shadows-support-v4:3.0"

2、建立Test类


3、配置Test环境

4、进行单元测试(三步:setUp、test、assert)

编写完后运行

部分代码如下:

1、添加依赖

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:24.2.1'
    //安卓自带测试依赖
    testCompile 'junit:junit:4.12'
    //robolectric 依赖
    testCompile "org.robolectric:robolectric:3.0"
    //assertj 依赖
    testCompile 'org.assertj:assertj-core:1.7.1'

    //测试Fragment需要添加的依赖
    testCompile "org.robolectric:shadows-support-v4:3.0"
}

android {
    useLibrary 'org.apache.http.legacy'
}

2、编写代码(部分)

package com.leixiansheng.unittest;

import android.content.Intent;
import android.os.Bundle;
import android.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity implements OnClickListener{
    private Button btnIntent;
    private Button btnInverse;              //点击改变checkBox状态
    private Button btnShowDialog;           //显示提示框
    private Button btnShowToast;
    private Button sendBroadcast;
    private CheckBox checkBox;
    private TextView textView;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        setTitle("test title");
        initView();
        addClick();
    }

    private void addClick() {
        btnIntent.setOnClickListener(this);
        btnInverse.setOnClickListener(this);
        btnShowToast.setOnClickListener(this);
        btnShowDialog.setOnClickListener(this);
        sendBroadcast.setOnClickListener(this);
    }

    private void initView() {
        btnIntent = (Button) findViewById(R.id.btn_intent);
        btnInverse = (Button) findViewById(R.id.btn_inverse);
        btnShowDialog = (Button) findViewById(R.id.btn_show_dialog);
        btnShowToast = (Button) findViewById(R.id.btn_toast);
        checkBox = (CheckBox) findViewById(R.id.checkbox);
        textView = (TextView) findViewById(R.id.text_view);
        sendBroadcast = (Button) findViewById(R.id.btn_send_broadcast);
    }

    boolean change = false;
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_intent:
                startActivity(new Intent(MainActivity.this, SecondActivity.class));
                break;
            case R.id.btn_inverse:
                  if (change) {
                      checkBox.setChecked(true);
                  } else {
                      checkBox.setChecked(false);
                  }
                  change = !change;
                break;
            case R.id.btn_show_dialog:
                  AlertDialog.Builder builder = new AlertDialog.Builder(this);
                  builder.setTitle("builder").setMessage("this is a dialog").show();
                break;
            case R.id.btn_toast:
                Toast.makeText(this, "this is the toast",Toast.LENGTH_SHORT).show();
                break;
            case R.id.btn_send_broadcast:
                  sendBroadcast(new Intent("com.leixiansheng.RECEIVER"));
                break;
        }
    }

    /**
     * 加法
     */
    public int add(int a, int b) {
        return a+b;
    }

    @Override
    protected void onResume() {
        super.onResume();
        textView.setText("onResume");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        textView.setText("onDestroy");
    }
}

3、测试环境搭建,编写测试代码

package com.leixiansheng.unittest;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.app.AlertDialog;
import android.content.SharedPreferences;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.TextView;

import com.leixiansheng.unittest.broadcast.BroadReceiver;
import com.leixiansheng.unittest.fragment.SampleFragment;
import com.leixiansheng.unittest.intent.FirstActivity;
import com.leixiansheng.unittest.intent.SecondActivity;
import com.leixiansheng.unittest.intent.ThirdActivity;
import com.leixiansheng.unittest.service.SampleService;


import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.Robolectric;
import org.robolectric.RobolectricGradleTestRunner;
import org.robolectric.RuntimeEnvironment;
import org.robolectric.Shadows;
import org.robolectric.annotation.Config;
import org.robolectric.fakes.RoboSharedPreferences;
import org.robolectric.shadows.ShadowActivity;
import org.robolectric.shadows.ShadowAlertDialog;
import org.robolectric.shadows.ShadowApplication;
import org.robolectric.shadows.ShadowToast;
import org.robolectric.shadows.support.v4.SupportFragmentTestUtil;
import org.robolectric.util.ActivityController;

import static org.assertj.core.api.Assertions.*;


@RunWith(RobolectricGradleTestRunner.class)
@Config(constants = BuildConfig.class, sdk = 21)
public class MainActivityTest {
    private MainActivity mainActivity;
    private SecondActivity secondActivity;
    private FirstActivity firstActivity;
    private ThirdActivity thirdActivity;

    private ActivityController<MainActivity> activityController;

    private TextView textView;
    private Button btnInverse;
    private Button btnIntent;
    private Button btnToast;
    private CheckBox checkBox;
    private Button showDialog;
    private Button sendBroadcast;

    @Before
    public void setUp() throws Exception{
        //获取活动实例
        mainActivity = Robolectric.setupActivity(MainActivity.class);
        firstActivity = Robolectric.setupActivity(FirstActivity.class);
        secondActivity = Robolectric.setupActivity(SecondActivity.class);
        thirdActivity = Robolectric.setupActivity(ThirdActivity.class);

        //模拟onCreate onStart
        activityController = Robolectric.buildActivity(MainActivity.class)
                .create().start();
        Activity activity = activityController.get();

        textView = (TextView) activity.findViewById(R.id.text_view);
        btnInverse = (Button) mainActivity.findViewById(R.id.btn_inverse);
        checkBox = (CheckBox) mainActivity.findViewById(R.id.checkbox);
        showDialog = (Button) mainActivity.findViewById(R.id.btn_show_dialog);
        btnToast = (Button) mainActivity.findViewById(R.id.btn_toast);
        btnIntent = (Button) firstActivity.findViewById(R.id.btn_intent);
        sendBroadcast = (Button) mainActivity.findViewById(R.id.btn_send_broadcast);
    }

    /**
     * 创建活动实例
     */
    @Test
    public void testActivity() {
        assertThat(mainActivity).isNotNull();
//        assertEquals("test title", mainActivity.getTitle().toString());
        assertThat("test title").isEqualTo(mainActivity.getTitle());
    }

    /**
     * 生命周期
     * 只有使用 ActivityController 才能模拟安卓生命周期
     */
    @Test
    public void testLifestyle() {
//        assertEquals("Hello World!",textView.getText().toString());
        assertThat(textView.getText().toString()).isEqualTo("Hello World!");
        //模拟 onResume
        activityController.resume();
        assertThat(textView.getText().toString()).isEqualTo("onResume");
        //模拟 onDestroy
        activityController.destroy();
        assertThat(textView.getText().toString()).isEqualTo("onDestroy");
    }

    /**
     * 测试跳转
     */
    @Test
    public void testMainActivity() {
        //模拟点击动作
        btnIntent.performClick();

        //实际结果
        ShadowActivity shadowActivity = Shadows.shadowOf(firstActivity);
        Intent actualIntent = shadowActivity.getNextStartedActivity();
        //结果判定
        assertThat(actualIntent.getComponent().getClassName()).isEqualTo(secondActivity.getComponentName().getClassName());
    }

    /**
     * UI 组件状态
     */
    @Test
    public void testViewState() {
        checkBox.setChecked(true);

        //模拟点击翻转按钮
        btnInverse.performClick();
        assertThat(!checkBox.isChecked()).isTrue();

        btnInverse.performClick();
        assertThat(checkBox.isChecked()).isTrue();
    }

    /**
     * Dialog
     */
    @Test
    public void testDialog() {
        showDialog.performClick();
        //注意这里的AlertDialog 只支持 android.app  不是support v7
        AlertDialog latestAlertDialog = ShadowAlertDialog.getLatestAlertDialog();
        assertThat(latestAlertDialog).isNotNull();
        assertThat(latestAlertDialog.isShowing()).isTrue();
    }

    /**
     * 自定义方法测试(加法)
     */
    @Test
    public void testAdd() {
        int result = mainActivity.add(10, 30);
        assertThat(result).isEqualTo(40);
    }

    /**
     * Toast
     */
    @Test
    public void testToast() {
        btnToast.performClick();
        String toastText = ShadowToast.getTextOfLatestToast();
        assertThat(toastText).isEqualTo("this is the toast");
    }

    /**
     * 访问资源文件
     */
    @Test
    public void testResources() {
        Application application = RuntimeEnvironment.application;
        String appName = application.getString(R.string.app_name);
        assertThat(appName).isEqualTo("UnitTest");
    }

    /**
     * Broadcast
     */
    @Test
    public void testBroadcast() {
        sendBroadcast.performClick();
        ShadowApplication shadowApplication = ShadowApplication.getInstance();

        String action = "com.leixiansheng.RECEIVER";
        Intent intent = new Intent(action);
        intent.putExtra("EXTRA_USERNAME", "xiao ming");

        BroadReceiver receiver = new BroadReceiver();
        receiver.onReceive(RuntimeEnvironment.application,intent);
        SharedPreferences preferences = shadowApplication.getSharedPreferences("account", Context.MODE_PRIVATE);
        System.out.print(preferences.getString("USERNAME",""));
        //比较结果
        assertThat(preferences.getString("USERNAME","")).isEqualTo("xiao ming");
    }

    /**
     * Service
     */
    @Test
    public void testService() {
        Application application = RuntimeEnvironment.application;
        RoboSharedPreferences preferences = (RoboSharedPreferences) application.getSharedPreferences("example", Context.MODE_PRIVATE);

        SampleService service = new SampleService();
        service.onHandleIntent(new Intent());

        assertThat(preferences.getString("SAMPLE_DATA", "")).isEqualTo("sample data");
    }

    /**
     * fragment
     */
    @Test
    public void testFragment() {
        SampleFragment sampleFragment = new SampleFragment();
        //此api可以主动添加Fragment到Activity中,因此会触发Fragment的onCreateView()
        SupportFragmentTestUtil.startFragment(sampleFragment);
        assertThat(sampleFragment.getView()).isNotNull();
    }
}

代码覆盖率:

1、测试类右键,选择下图运行方式

2、在执行完后弹出的简略窗口选择导出即可查看详细代码覆盖率



 


 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值