一、JUnit介紹
Junit是 Erich Gamma 和 Kent Beck編寫的測試架構,是我們在軟體工程所說的白盒測試。
使用也很簡單,只需要在Eclipse匯入JAR包即可;
:https://github.com/downloads/KentBeck/junit/junit4.10.zip
二、JUnit4和JUnit3的比較
| JUnit3 |
JUnit4 |
| 測試類別需要繼承TestCase |
不需要繼承任何類 |
| 測試函數約定:public、void、test開頭、無參數 |
需要在測試函數前面加上@Test |
每個測試函數之前setUp執行 |
@Before |
| 每個測試函數之後tearDown執行 |
@After |
| 沒有類載入時執行的函數 |
@BeforeClass和@AfterClass |
三、JUnit4詳解
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;}}
PersonTest.java
此測試是用JUnit3測試的;
package org.xiazdong.junit;import junit.framework.Assert;import junit.framework.TestCase;import org.xiazdong.Person;public class PersonTest extends TestCase {@Overrideprotected void setUp() throws Exception {System.out.println("setUp");}@Overrideprotected 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());}}
PersonTest2.java
此測試是用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 {@Beforepublic void before(){System.out.println("before");}@Afterpublic void after(){System.out.println("After");}@BeforeClasspublic void beforeClass(){System.out.println("BeforeClass");}@AfterClasspublic void afterClass(){System.out.println("AfterClass");}@Testpublic void testFun1(){Person p = new Person("xiazdong",20);Assert.assertEquals("xiazdong", p.getName());Assert.assertEquals(20, p.getAge());}@Testpublic void testFun2(){Person p = new Person("xiazdong",20);Assert.assertEquals("xiazdong", p.getName());Assert.assertEquals(20, p.getAge());}}