JUnit4 学习总结

来源:互联网 发布:mac子弹头最火的色号 编辑:程序博客网 时间:2024/06/04 19:24

一、JUnit介绍

Junit是 Erich Gamma 和 Kent Beck编写的测试框架,是我们在软件工程所说的白盒测试。

使用也很简单,只需要在Eclipse导入JAR包即可;

下载地址:https://github.com/downloads/KentBeck/junit/junit4.10.zip

 

二、JUnit4和JUnit3的比较

 

JUnit3JUnit4测试类需要继承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());}}