Calculator.java文件
package com.ljl.junit;
public class Calculator {
public int add(int a, int b) {
return a + b;
}
public int substract(int a, int b) {
return a - b;
}
public int multiply(int a, int b) {
return a * b;
}
public int divide(int a, int b) throws Exception {
if(0 == b){
throw new Exception("the divisor should not be zero");
}
return a / b;
}
public int square(int n) {
return n * n;
}
public void squareRoot(int n) {
for (;;)
;
}
}
测试文件
CalculatorTest.java
package com.ljl.junit;
import static org.junit.Assert.*;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
public class CalculatorTest {
Calculator calculator = null;
@BeforeClass
public static void setUpBeforeClass() throws Exception{
System.out.println("beforeClass");
}
@AfterClass
public static void tearDownAfterClass() throws Exception{
System.out.println("AfterClass");
}
@Before
public void setUp() throws Exception{
calculator = new Calculator();
System.out.println("before");
}
@After
public void tearDown() throws Exception{
System.out.println("after");
}
@Test
public void testAdd() {
int result = calculator.add(1, 2);
assertEquals(result,3);
}
@Test
public void testSubstract() {
int result = calculator.substract(7, 6);
assertEquals(result,1);
}
@Test
public void testMultiply() {
int result = calculator.multiply(-3, -3);
assertEquals(result,9);
}
@Test(expected = Exception.class)//异常处理
public void testDivide() throws Exception {
calculator.divide(2, 0);
}
@Test
public void testSquare() {
int result = calculator.square(-2);
assertEquals(result,4);
}
@Ignore
@Test(timeout = 100)//等待执行时间
public void testSquareRoot() {
calculator.squareRoot(4);
}
}
多个测试数据打包测试
package com.ljl.junit; import static org.junit.Assert.assertEquals; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; import java.util.Arrays; import java.util.Collection; @RunWith(Parameterized.class) public class AddTest { private static Calculator calculator = new Calculator(); private int val1; private int val2; private int sum; @Parameters public static Collection data() { return Arrays.asList(new Object[][]{ {1,3,4}, {2,4,6}, {-3,3,0}, }); } //构造函数,对变量进行初始化 public AddTest(int val1, int val2, int sum) { this.val1 = val1; this.val2 = val2; this.sum = sum; } @Test public void AddTest() { int tmp = calculator.add(val1, val2); assertEquals(sum,tmp); } }
参考http://tips1000.com/archives/189.html