JUnit is a simple framework to write repeatable tests. It is an instance of the xUnit architecture for unit testing frameworks.
单元测试的重要性:1、测试重用;2、增强程序健壮性; 3、降低维护成本;
hamcrest 断言 :assertThat 更加符合自然语言
JUnit 4 annotation (@Test 、 、、、、)
注意:1、类放在test 包中;2、类名用XXXTest 结尾; 3、方法用testXXX命名。
package junit; public class Hello { public int add(int x, int y){ return x + y ; } public int divide(int x, int y){ return x/y ; } }
package junit.test; 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; import junit.Hello; import static org.hamcrest.Matchers.*; public class HelloTest { @BeforeClass //所有测试开始之前运行 public static void beforeclass(){ System.out.println("beforeclass"); } @AfterClass public static void afterclass(){ System.out.println("afterclass"); } @Before // 每一个测试方法之前运行 public void before(){ System.out.println("before"); } @Test //测试方法 public void testAdd() { int z = new Hello().add(3, 5); assertEquals(8, z); assertThat(z, is(8)); } @Ignore @Test public void testDivide(){ int d = new Hello().divide(8,4); assertEquals(d , 2); } @After // 每一个测试方法之后运行 public void after(){ System.out.println("after"); } }