创建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 CollectiongetTestParameters() { 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); } }
注:通过注解运行参数化测试