Junit 使用

来源:互联网 发布:人工智能 杂志 中文 编辑:程序博客网 时间:2024/05/17 23:23

JUnit是用于编写和运行可重复的自动化测试的开源测试框架.它是一个Java语言的单元测试框架,简单理解:可以用于取代java的main方法。

使用步骤:
1.创建java项目JunitDemo,在工程上点击右键,选择:Build Path -> Add Library -> JUnit …,如下图所示:
junit01
junit02
junit03
2.创建测试类,编写测试方法,进行测试
1)测试方法名一般以test开头,测试方法无返回值,无参数。
2)测试方法上添加@Test
3)右击方法名,选择run as ——> Junit Test 执行单元测试
示例:

package singleton.test;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.ObjectInputStream;import java.io.ObjectOutputStream;import org.junit.Assert;import org.junit.Test;public class DemoTest{    @Test    public void test() throws Exception{        SerSingleton s1 = null;        SerSingleton s = SerSingleton.getInstance();        //先将实例串行化到文件        FileOutputStream fos = new FileOutputStream("H:/code/singleton/SerSingleton.text");        ObjectOutputStream oos = new ObjectOutputStream(fos);        oos.writeObject(s);        oos.flush();        oos.close();        //从文件读取原有的单例类        FileInputStream fis = new FileInputStream("H:/code/singleton/SerSingleton.text");        ObjectInputStream ois = new ObjectInputStream(fis);        s1 = (SerSingleton) ois.readObject();        Assert.assertEquals(s, s1);//通过断言判断执行结果    }}

备注:
* @Test 用于修饰需要测试方法
* @Before 表示在测试方法前执行的方法
* @After 表示在测试方法后执行的方法

原创粉丝点击