JUnit4 學習總結

來源:互聯網
上載者:User
一、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());}}

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.