Junit是 Erich Gamma 和 Kent Beck编写的测试框架,是我们在软件工程所说的白盒测试。
使用也很简单,只需要在Eclipse导入JAR包即可;
下载地址:https://github.com/downloads/KentBeck/junit/junit4.10.zip
JUnit3 | JUnit4 |
测试类需要继承TestCase | 不需要继承任何类 |
测试函数约定:public、void、test开头、无参数 | 需要在测试函数前面加上@Test |
每个测试函数之前setUp执行 |
@Before |
每个测试函数之后tearDown执行 | @After |
没有类加载时执行的函数 | @BeforeClass和@AfterClass |
1.@Test用来标注测试函数
2.@Before用来标注此函数在每次测试函数运行之前运行
3.@After用来标注此函数在每次测试函数运行之后运行
4.@BeforeClass用来标注在测试开始时运行;
5.@AfterClass 用来标注在测试结束时运行;
6.Assert类中有很多断言,比如assertEquals("期望值","实际值");
代码示例:
Person.java
package org.xiazdong; public class Person { private String name; private int age; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public Person(String name, int age) { this.name = name; this.age = age; } }
此测试是用JUnit3测试的;
package org.xiazdong.junit; import junit.framework.Assert; import junit.framework.TestCase; import org.xiazdong.Person; public class PersonTest extends TestCase { @Override protected void setUp() throws Exception { System.out.println("setUp"); } @Override protected void tearDown() throws Exception { System.out.println("tearDown"); } public void testFun1(){ Person p = new Person("xiazdong",20); Assert.assertEquals("xiazdong", p.getName()); Assert.assertEquals(20, p.getAge()); } public void testFun2(){ Person p = new Person("xiazdong",20); Assert.assertEquals("xiazdong", p.getName()); Assert.assertEquals(20, p.getAge()); } }
此测试是用JUnit4测试的;
package org.xiazdong.junit; import junit.framework.Assert; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.xiazdong.Person; public class PersonTest2 { @Before public void before(){ System.out.println("before"); } @After public void after(){ System.out.println("After"); } @BeforeClass public void beforeClass(){ System.out.println("BeforeClass"); } @AfterClass public void afterClass(){ System.out.println("AfterClass"); } @Test public void testFun1(){ Person p = new Person("xiazdong",20); Assert.assertEquals("xiazdong", p.getName()); Assert.assertEquals(20, p.getAge()); } @Test public void testFun2(){ Person p = new Person("xiazdong",20); Assert.assertEquals("xiazdong", p.getName()); Assert.assertEquals(20, p.getAge()); } }