SimpleJunit4 Test
public class SimpleJunit {
@Before public void setUp(){
//such as initialize db connection
}
@Test public void test0(){
assertEquals(1,1);
assertNull(null);
//org.junit.Assert....
}
@After public void teardown(){
//such as close db connection
}
}
junit4执行顺序
BeforeClass ->[Before->Test-After,Before->Test-After]->AfterClass
junit4的类变量,非static变量在每次Test都会恢复到类定义是的值
Private String var1=“123”;
Private static String var2=“345”;
@Test public void test0{System.out.println(var1); System.out.println(var2);
var1=“678”;var2=“789”};//123,345
@Test public void test1{System.out.println(var1); System.out.println(var2);//123,789
想一次测试多个用例
import org.junit.runner.RunWith;
import org.junit.runners.Suite.SuiteClasses;
import org.junit.runners.Suite;
@RunWith(value = Suite.class)
@SuiteClasses(value={ProductControllerTest.class,
POPISpringTest.class })
public class SuiteTest{ }
也可右键包文件夹进行批量执行,但不能选择多个文件执行
忽略某个方法
@Ignore("暂时不测了")
@Test public void test0(){}
单独测试某个方法
右键点击方法名进行测试
Junit4Assert 一些常见的Assert
assertEquals(expect,actual);
assertEquals(double expect,double actual,double delta)
可以在delta指定的差异范围内判断是否相等,如asserEquals(1,1.001,0.01) is true
assertEquals(1,1.002,0.001) is false,because 1.002-1=0.002>0.001
assertEquals([message],expect,actual);
message 会在不等的情况下输出,如assertEquals("It's wrong", 1, 0);
//It's wrong expected:<1> but was:<0>
assertSame(expect,actual) 是通过 expect == actual 判断的
assertThat([String reason], T actual,Matcher<T> matcher)
Matcher是由 Hamcest提供的一套匹配符,它更接近自然语言,可读性高,更加灵活
如assertThat(“Junit is a wonderfull tool", StringContains.containsString("C#")); is false
fail
多用于发生异常时
hamcrest Matcher
assertThat("C#",org.hamcrest.core.IsEqual.equalTo("C#"));
assertThat("C# is a wonderful language",org.hamcrest.core.StringEndsWith.endsWith("language"));
assertThat(5,org.hamcrest.core.AllOf.allOf(org.hamcrest.number.OrderingComparison.greaterThan(6), org.hamcrest.number.OrderingComparison.lessThan(8)));
其他的可以“点”出来,不知道怎么用的最好还是看看源代码