zoukankan      html  css  js  c++  java
  • 在Android studio环境下使用junit框架进行单元测试

    在软件开发过程中,测试是一个非常重要的环节.其中单元测试可以由程序编写者来完成,在Android studio环境下可以使用Junit框架来进行单元测试.

    首先, 在gradle里面添加Junit的支持:

    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:25.1.1'
        compile 'com.android.support.constraint:constraint-layout:1.0.1'
        testCompile 'junit:junit:4.12'
    }

    建立一个被测试类,我选择了计算最大子数组和作为被测试类的运算法则;

    package com.example.test;
    
    public class Array {
    
        //获取最大子数组
        public int list(int[] list) {
            int summax = max(list);
            int i, j, k;
            for (i = 0; i < list.length; i++)
                for (j = i; j < list.length; j++) {
                    int temp = 0;
                    for (k = i; k <= j; k++)
                        temp += list[k];
                    if (temp > summax) {
                        summax = temp;
                    }
                }
            return summax;
    
        }
    
        //获取数组的最大值
        public int max(int[] list) {
            int max = list[0];
            for (int i = 0; i < list.length; i++) {
                if (max < list[i]) {
                    max = list[i];
                }
            }
            return max;
        }
    
    }

    在被测试类内右击选择 GoTu再选择test,

    再选择creat new test...

    选中需要测试的类名list,修改测试类的名称ArrayTest

    在测试类中,编写测试用例,使用assertEquals方法判断被测试类的运行是否正确,ArrayList数组的最大子数组和是-1.

    package com.example.test;
    
    import org.junit.After;
    import org.junit.Before;
    import org.junit.Test;
    
    import static org.junit.Assert.assertEquals;
    
    public class ArrayTest {
        private Array mArray;int[] ArrayList = {-2,-3,-5,-1,-9};
    @Before
    public void setUp() throws Exception { mArray = new Array(); } @After public void tearDown() throws Exception { } @Test public void list() throws Exception { assertEquals(-1, mArray.list(ArrayList), 0); } }

    测试用例编写完成后,右击 ArrayTest方法,选中run,

    如果测试通过,就显示passed

    如果未通过,就显示failed,并在下方显示错误位置

  • 相关阅读:
    STM32 + RT Thread OS 学习笔记[三]
    全代码实现ios-1
    HTML5 Web Speech API 结合Ext实现浏览器语音识别以及输入
    全代码实现ios-2
    从零开始学C++之虚函数与多态(一):虚函数表指针、虚析构函数、object slicing与虚函数
    二进制程序分析工具Pin在Windows系统中的安装和使用方法
    使用U盘安装Ubuntu系统的实践小结
    HDU 1874 畅通工程续
    JSP页面上用横线代替文本框
    Mysql设置编码
  • 原文地址:https://www.cnblogs.com/Minrcrafter/p/6558736.html
Copyright © 2011-2022 走看看