目录结构:
D:\code\kongee\junit_01>tree /f 卷 软件 的文件夹 PATH 列表 卷序列号为 000D-CD8E D:. │ .classpath │ .project │ ├─.settings │ org.eclipse.jdt.core.prefs │ ├─bin │ └─com │ └─laolang │ └─modle │ Cal.class │ Student.class │ TestA.class │ TestCal.class │ TestSuite.class │ ├─lib │ hamcrest-all-1.3.jar │ hamcrest-core-1.3.jar │ junit-4.11.jar │ ├─src │ └─com │ └─laolang │ └─modle │ Cal.java │ Student.java │ └─test └─com └─laolang └─modle TestA.java TestCal.java TestSuite.java D:\code\kongee\junit_01>在项目中新建一个source folder,命名为test
在test中新建一个与测试类同名的包,然后写测试类
src/com.laolang.modle.Cal
package com.laolang.modle; public class Cal { public int add( int a, int b){ return a + b; } public int minus( int a, int b){ return a - b; } public int mult( int a, int b){ return a * b; } public int divide( int a, int b){ return a / b; } }test/com.laolang.modle.TestCal
package com.laolang.modle; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.*; import static org.hamcrest.Matchers.*; public class TestCal { @Before public void setUp(){ cal = new Cal(); } @Test public void testAdd(){ int result = cal.add(1, 3); int real = 4; Assert.assertEquals("加法有问题!",real, result); } @Test public void testMinus(){ int result = cal.minus(1, 6); int real = -5; Assert.assertEquals("减法有问题!",real, result); } @Test public void testMult(){ int result = cal.mult(2, 8); int real = 16; Assert.assertEquals("乘法有问题!",real, result); } @Test public void testDivide(){ int result = cal.divide(9, 3); int real = 3; Assert.assertEquals("除法有问题!",real, result); } @Test public void testTimeout(){ try { Thread.sleep(200); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("hello world!"); } @Test public void testHamcrest(){ assertThat(50,allOf(greaterThan(40),lessThan(60))); assertThat(50, greaterThan(40)); } private Cal cal; }
写测试类的基本步骤:
1、导入junit包
2、静态导入
import static org.junit.Assert.*; import static org.hamcrest.Matchers.*;
原文:http://my.oschina.net/iamhere/blog/523292