最简单的例子介绍Junit测试框架
public class Person { public void run() { System.out.println("run!!!"); } public void eat() { System.out.println("eat!!!"); } public static void main(String[] args){ System.out.println("miao"); } }
import org.junit.After; import org.junit.Before; import org.junit.Test; //Person类的测试类 public class test { private Person p; //@Before、@Test、@After 是关键 没有这个标志不能生成Junit测试 @Before public void before() { System.out.println("before"); p = new Person(); } @Test public void testRun() { p.run(); } @Test public void testEat() { p.eat(); } @After public void after() { System.out.println("after"); p = null; } }输出:
before
run!!!
after
before
eat!!!
after
import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; //Person类的测试类 public class test { //@BeforeClass、@Test、@AfterClass 是关键 没有这个标志不能生成Junit测试 @BeforeClass public static void beforeClass() { System.out.println("before"); } @Test public void testRun() { Person p = new Person(); p.run(); } @Test public void testEat() { Person p = new Person(); p.eat(); } @AfterClass public static void afterClass() { System.out.println("after"); } }输出:
before
run!!!
eat!!!
after
public class Person { public String run() { // System.out.println("run!!!"); return "1"; } public void eat() { System.out.println("eat!!!"); } public static void main(String[] args){ System.out.println("miao"); } }
import org.junit.Assert; import org.junit.Test; //Person类的测试类 public class test { // @Test 是关键 没有这个标志不能生成Junit测试 @Test public void testRun() { Person p = new Person(); //p.run(); //断言 Assert.assertEquals("1",p.run()); //测试预期的结果和运行的结果是否一致(测试通过,绿条) Assert.assertEquals("2",p.run()); //测试预期的结果和运行的结果是否一致(测试不通过,红条) //Assert还有很多类方法具体可查询api } @Test public void testEat() { Person p = new Person(); p.eat(); } }