转载请注明出处: http://qiudeqing.com/java_web/2016/01/11/junit.html

安装

pom.xml添加依赖, 设置scope为test

<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
</dependency>

helloworld

1) 新建src/main/java/com/qiudeqing/app/Calculator.java

package com.qiudeqing.app;

public class Calculator {

    public int evaluate(String expression) {
        int sum = 0;
        for (String summand: expression.split("\\+")) {
            sum += Integer.valueOf(summand);
        }
        return sum;
    }

}

2) 新建src/test/java/com/qiudeqing/app/CalculatorTest.java

package com.qiudeqing.app;

import static org.junit.Assert.assertEquals;
import org.junit.Test;

public class CalculatorTest {

    @Test
    public void evaluatesExpression() {
        Calculator calculator = new Calculator();
        int sum = calculator.evaluate("1+2+3");
        assertEquals(6, sum);
    }
}

3) 命令行执行mvn test运行测试用例, 或者在Eclipse单独运行, 测试成功

4) 尝试失败

修改Caclulator.java

sum += Integer.valueOf(summand);

替换为

sum -= Integer.valueOf(summand);

此时运行mvn test显示失败