码迷,mamicode.com
首页 > 其他好文 > 详细

JUnit实战(1) - JUnit起步(Parameterized参数化测试)

时间:2015-02-05 23:04:23      阅读:158      评论:0      收藏:0      [点我收藏+]

标签:

创建Java Project项目,项目名称:ch01-jumpstart

Calculator.java

public class Calculator {
    public double add(double number1, double number2) {
        return number1 + number2;
    }
}

CalculatorTest.java

import static org.junit.Assert.*;
import junit.framework.Assert;

import org.junit.Test;

public class CalculatorTest {
    @Test
    public void testAdd() {
        Calculator calculator = new Calculator();
        double result = calculator.add(10, 50);
        assertEquals(60, result, 0);
    }
}

注:使用静态导入可以使被导入类的静态变量和静态方法在当前类直接可见,使用这些静态成员无需再给出他们的类名(如assertEquals(double expected, double actual, double delta))。

ParameteredCalculatorTest.java

import static org.junit.Assert.assertEquals;

import java.util.Arrays;
import java.util.Collection;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;

@RunWith(value=Parameterized.class)
public class ParameterizedCalculatorTest {

    private double expected; 
    private double valueOne; 
    private double valueTwo; 

    @Parameters 
    public static Collection<Integer[]> getTestParameters() {
       return Arrays.asList(new Integer[][] {
          {2, 1, 1},  //expected, valueOne, valueTwo   
          {3, 2, 1},  //expected, valueOne, valueTwo   
          {4, 3, 1},  //expected, valueOne, valueTwo   
       });
    }

    public ParameterizedCalculatorTest(double expected, 
       double valueOne, double valueTwo) {
       this.expected = expected;
       this.valueOne = valueOne;
       this.valueTwo = valueTwo;
    }

    @Test
    public void sum() {
       Calculator calc = new Calculator();
       assertEquals(expected, calc.add(valueOne, valueTwo), 0);
    } 
}

注:通过注解运行参数化测试

JUnit实战(1) - JUnit起步(Parameterized参数化测试)

标签:

原文地址:http://www.cnblogs.com/thlzhf/p/4276005.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!