Junit4测试Calculator
Calculator代码:
package cn.itcast; import org.junit.Before; public class Calculator { private static int result; // 静态变量,用于存储运行结果 public void add(int n) { result = result + n; } public void substract(int n) { result = result - 1; //故意的Bug,应该是 result =result-n } public void multiply(int n) { } // 假设此方法在项目完成过程中尚未写好 public void divide(int n) { result = result / n; } public void square(int n) { result = n * n; } public void squareRoot(int n) { //求平方根 for (; ;) ; //Bug : 死循环 } public void clear() { // 将结果清零 result = 0; } public int getResult(){ return result; } }
创建Test,在class处按shift+ctrl+T进行创建
Test代码:
package cn.itcast; import org.junit.Ignore; import org.junit.Test; import static org.junit.Assert.*; public class CalculatorTest { Calculator calculator = new Calculator(); @Test public void add() { calculator.add(10); assertEquals(calculator.getResult(),10); } @Test public void substract() { calculator.add(10); calculator.substract(10); assertEquals(calculator.getResult(),0); } @Ignore("该方法未实现") public void multiply() { calculator.multiply(10); } @Test public void divide() { calculator.divide(0); } @Test public void square() { calculator.square(10); assertEquals(calculator.getResult(),100); } @Test(timeout = 2000) public void squareRoot() { calculator.squareRoot(4); assertEquals(calculator.getResult(),2); } @Test public void clear() { calculator.clear(); assertEquals(calculator.getResult(),0); } }
运行后可以查看是否通过测试