您的当前位置:首页正文

JUnit4单元测试简单入门

来源:东饰资讯网

本文主要介绍在android studio中进行单元测试的方式,你将了解到
1.如何在android studio中引用JUnit4
2.单元测试Demo

引用模块

然后在build.gradle中添加

compile 'com.jakewharton.espresso:espresso:1.1-r3'~~~

Demo
新建一个Calculator 测试它的方法

package com.example.news;

/**

  • Created by 小新 on 2016/7/1.
    */
    public class Calculator {
    public double sum(double a, double b){
    return a+b;
    }

    public double substract(double a, double b){
    return a-b;
    }

    public double divide(double a, double b){
    return a/b;
    }

    public double multiply(double a, double b){
    return a*b;
    }

    public double addMore(double a,double b,double c){

     return a+b+c;
    

    }

}

在类名上面点击右键生成test测试类




会在测试类的包中自动生成测试类

package com.example.news;

import org.junit.Before;
import org.junit.Test;

import static org.junit.Assert.*;

/**

  • Created by 小新 on 2016/7/1.
    */
    public class CalculatorTest {

    @Before
    public void setUp() throws Exception {

    }

    @Test
    public void testSum() throws Exception {

    }

    @Test
    public void testSubstract() throws Exception {

    }

    @Test
    public void testDivide() throws Exception {

    }

    @Test
    public void testMultiply() throws Exception {

    }

    @Test
    public void testAddMore() throws Exception {

    }
    }

然后进行测试

package com.example.news;

import org.junit.Before;
import org.junit.Test;

import static org.junit.Assert.*;

/**

  • Created by 小新 on 2016/7/1.
    */
    public class CalculatorTest1 {
    private Calculator calculator;

    @Before
    public void setUp() throws Exception {
    calculator = new Calculator();

    }

    @Test
    public void testSum() throws Exception {
    //测试sum函数,因为sum函数返回的是两个数的合为3
    //这里期望返回的值是9
    //所以会报错
    assertEquals(9d,calculator.sum(1d,2d),0);
    }

    @Test
    public void testSubstract() throws Exception {

    }

    @Test
    public void testDivide() throws Exception {

    }

    @Test
    public void testMultiply() throws Exception {

    }

    @Test
    public void testAddMore() throws Exception {

    }
    }

运行这个类,结果为报错,这个时候我们就需要修改函数了
到这里我们JUnix的简单测试就结束了
显示全文