JUnit4 學習總結
一、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 { @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()); } }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 { @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()); } }轉自:http://blog.csdn.net/xiazdong/article/details/7317376
本文由用戶 openkk 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!