JUnit java单元测试

首先须导入JUnit包:所在项目右击->Build Path->Add Libraries->选择JUnit->选择一个版本->Finish

一.手动生成

1.测试方法,必须符合下列条件

* 方法必须声明成:public,void

* JUnit3方法名必须以test开头,JUnit4则不需要

* 方法无参数

          如:

JUnit3:Public void testAdd(){}

JUnit4:@Test (org.junit.Test)

Public void AddTest(){}

2. JUit3 与 JUit4的区别

        源码和测试代码分开放在不同的Source Folder,测试代码所在的包名最好和源码中的包名一一对应。JUnit3测试方法中的类必须继承TestCase(junit.framwork.TestCase);而JUnit4类则不需要继承任何类,但在方法前须加上注解@Test(org.junit.Test)此测试方法,标注该程序是以JUnit的方式来运行的。

       JUit3:在方法前加上TestCase类的方法setUp(),在执行每一次测试方法之前都会被调用,可把在测试方法中都需要的程序放在这里;最后加上tearDown()方法,在执行每一次方法后都会被调用。

JUit4:与JUit3不同的是,在JUit4中是在方法前用注解

       @BeforeClass:globeInit(),无论执行多少测试方法,它只执行一次,且运行在最前

       @Before:把方法注解成Before,init()与JUit3中的setUp()方法作用一样

       @After:把方法注解成After,destroy()与JUit3中的tearDown ()方法作用一样

       @AfterClass:无论执行多少测试方法,它只执行一次,且运行在最后

下面分别以JUit3和JUit4为例子来运行测试:

要测试的类

package com.sinyee.unit;
public class ArrayUnit {
    /**
     *传入一个数组,返回该数组的最大值
     * @param array
     * @return
     */
    public int getMaxValue(int[] array) throws Exception {
        if (array == null) {
            throw new NullPointerException("空指针异常");
        }
        if (array.length == 0) {
            throw new ArrayIndexOutOfBoundsException("数组不能为空!");
        }
        int temp = array[0];
        for (int i = 1; i < array.length; i++) {
            if (temp < array[i]) {
                array[i] = temp;
            }
        }
        // 取出该数组的最大值
        return temp;
    }
}
1)用JUit3测试

       Junit3测试代码

package com.sinyee.unit;

import junit.framework.TestCase;

public class ArrayTest extends TestCase {

    // 设置类的成员变量,可以供所有的方法调用

    private ArrayUnit aUnit;

    /**
     * 
     * 该setUp()方法为TestCase里面的方法
     * 作用:在每次执行调用测试方法之前,会先调用该setUp方法
     */
    @Override
    protected void setUp() throws Exception {
        // 实例化数组工具对象
        aUnit = new ArrayUnit();
        System.out.println("setUp()");
    }
    
    /**
     * 
     * 求数组最大值的测试用例1:数组不为空
     */

    public void testGetMaxValue1() {
        // 定义一个array数组
        int[] array = { 40, 3, 2, 6, 9, 30, 4 };
        try {
            // 调用求数组最大值方法
            int actual = aUnit.getMaxValue(array);
            // 期望值为40
            int expected = 40;
            // 断言actual==expect
            assertEquals(expected, actual);
        } catch (Exception e) {
            e.printStackTrace();
            fail();
        }
    }

    /**
     * 
     * 求数组最大值的测试用例2:数组为空
     */
    public void testGetMaxValue2() {
        // 定义一个array数组
        int[] array = {};
        
        // 实例化数组对象
        ArrayUnit aUnit = new ArrayUnit();
        try {
            // 调用求数组最大值方法
            aUnit.getMaxValue(array);

            // 若上面的方法有抛出异常,则fail()方法将不会被调用
            fail();
        } catch (Exception e) {
            // 断言该异常为ArrayIndexOutOfBoundsException该类型的异常,且消息为"数组不能为空!"
            assertEquals(ArrayIndexOutOfBoundsException.class, e.getClass());
            assertEquals("数组不能为空!", e.getMessage());
        }
    }

    /**
     * 
     * 求数组最大值的测试用例3:空指针异常
     */
    public void testGetMaxValue3() {
        int[] array = null;
        ArrayUnit aUnit = new ArrayUnit();
        try {
            aUnit.getMaxValue(array);
            fail();
        } catch (Exception e) {
            // 断言该异常为NullPointerException该类型的异常,且消息为"空指针异常"
            assertEquals(NullPointerException.class, e.getClass());
            assertEquals("空指针异常", e.getMessage());
        }
    }
    @Override
    protected void tearDown() throws Exception {
        System.out.println("tearDown()");
    }
}

 

2)用JUit4测试

测试代码:

package com.sinyee.unit;

import static org.junit.Assert.*;

import org.junit.After;
import org.junit.Before;
import org.junit.Ignore;

import org.junit.Test;

/**
 * 
 * Junit4的测试类 该类无需继承任何类,测试方法无需与test开头
 */

public class ArrayUnitTest {

    private ArrayUnit aUnit;

    /**
     * 把方法注解为@Before,效果与JUnit3中的setUp()方法一样
     */
    @Before
    public void init() {
        aUnit = new ArrayUnit();
    }

    /**
     * Junit4须加上@Test此测试方法,标注该程序是以Junit的方式来运行的 测试数组不为空
     */
    @Test
    public void getMaxValueTest() {
        int[] array = { 3, 6, 5, 7, 4, 8, 12, 0 };
        try {
            int actual = aUnit.getMaxValue(array);
            int expected = 12;
            // 断言expected==actual
            // Assert.assertEquals(expected, actual);

            // 或者也可以直接通过静态导入该Assert类的所有方法 import static org.junit.Assert.*;
            assertEquals(expected, actual);
        } catch (Exception e) {
            e.printStackTrace();
            fail();
        }
    }

    /**
     * 测试数组长度为零时,断言会抛出异常
     * 
     * @throws Exception
     */
    @Test(expected = ArrayIndexOutOfBoundsException.class)
    public void getMaxValueTest2() throws Exception {
        int[] array = {};
        aUnit.getMaxValue(array);
    }

    /**
     * 测试数组为null时,断言会抛出空指针异常
     * 
     * @throws Exception
     */
    @Test(expected = NullPointerException.class)
    public void getMaxValueTest3() throws Exception {
        int[] array = null;
        aUnit.getMaxValue(array);
    }

    /**
     * 当测试用例还未完成时,可用注解@Ignore来标记这测试用例还未完成
     */
    @Test
    @Ignore
    public void getMaxValueTest4() {

    }

    /**
     * 把方法注解为@After,效果与JUnit3中的tearDown()方法一样
     */
    @After
    public void destroy() {
    }

}
3).术语

       Errors程序出错

       Failures断言失败

 
4).批量测试
   4.1JUnit3
package com.sinyee.unit;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
public class AllTest extends TestCase {
    // 若要实现批量测试的话,须加上一个方法
    public static Test suite() {
        TestSuite tSuite = new TestSuite();

        // 添加计算器测试类
       tSuite.addTestSuite(CalculateTest.class);

        // 添加数组最大值测试类
      tSuite.addTestSuite(ArrayTest.class);

        // 添加堆栈测试类
        tSuite.addTestSuite(StackTest.class);
        return tSuite;
    }
}

   4.2JUnit4

package com.sinyee.unit;

import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;

    @RunWith(Suite.class)
    @SuiteClasses( { CalculateUtilTest.class, ArrayUnitTest.class,
        StackUtilTest.class, StringUtilTest.class })
    public class TestAll {
}

 

二.自动生成

        选择所要测试的类,右击->New->选择Java下的Junit项目中的Junit Test Case,根据自己所要测试的版本类型选择进行操作.

三.WEB测试

     需在lib包下拷入几个jar包:httpunit-1.7文件夹的lib目录下的httpunit.jar以及jars目录下的。

例:

package com.junit.action;
import static org.junit.Assert.*;
import java.io.IOException;
import org.junit.Test;
import org.xml.sax.SAXException;
import com.meterware.httpunit.GetMethodWebRequest;
import com.meterware.httpunit.PostMethodWebRequest;
import com.meterware.httpunit.WebConversation;
import com.meterware.httpunit.WebRequest;
import com.meterware.httpunit.WebResponse;
    public class UserLoginActionTest {
/**
* 测试用正确的网址登录,断言登录成功
*/
    @Test
    public void testDoGetHttpServletRequestHttpServletResponse() {
    //创建出模拟的浏览器对象
    WebConversation wc=new WebConversation();
    //创建出get请求
    WebRequest wRequest=new GetMethodWebRequest("http://localhost:8088/JUnitUserManage/UserLogin.html");
    try {

   //使用浏览器获取该请求的响应内容
    wc.getResponse(wRequest);
          } catch (IOException e) {

        e.printStackTrace();
        } catch (SAXException e) {

            e.printStackTrace();
       }
    }

    /**
    * 测试用一个不存在的地址登录,断言抛出异常
    * @throws SAXException
    * @throws IOException
    */
    @Test(expected=Exception.class)
    public void testDoGetHttpServletRequestHttpServletResponse2() throws IOException, SAXException     {
    //创建出模拟的浏览器对象
    WebConversation wc=new WebConversation();

    //创建出get请求
    WebRequest wRequest=new GetMethodWebRequest    ("http://localhost:8088/JUnitUserManage/UserLogin2.html");
    //使用浏览器获取该请求的响应内容
    wc.getResponse(wRequest);
}

    @Test
    public void testDoPostHttpServletRequestHttpServletResponse() {
    //创建出模拟的浏览器对象
    WebConversation wc=new WebConversation();

    //创建Post请求
    WebRequest wRequest=new PostMethodWebRequest    ("http://localhost:8088/JUnitUserManage/UserLogin.html");

    //模拟出请求所需要的参数
    wRequest.setParameter("userName", "admin");
    wRequest.setParameter("pwd", "admin");
        try {
    //获取该请求的响应内容
    WebResponse wResponse=wc.getResponse(wRequest);

    //获取响应内容的实际地址
    String actual=wResponse.getURL().toString();

    //期望在用户名和密码正确的情况下,跳转到页    //    面"http://localhost:8088/JUnitUserManage/Success.jsp"

    String expected="http://localhost:8088/JUnitUserManage/Success.jsp";

    //断言
    assertEquals(expected, actual);
        } catch (Exception e) {
            e.printStackTrace();
            fail();
        } 
    }

    /**
    * 测试失败页面的返回按钮的链接地址
    * 断言是"UserLogin.html"
    */
    @Test
    public void testLink(){
    //创建出模拟的浏览器对象
    WebConversation wc=new WebConversation();
    //创建出http://localhost:8088/JUnitUserManage/Failure.jsp:8088/JUnitUserManage/Failure.jsp该地址的get请求方式
    WebRequest wRequest=new GetMethodWebRequest    ("http://localhost:8088/JUnitUserManage/Failure.jsp");
    //获取该请求的响应内容
        try {
            WebResponse wResponse=wc.getResponse(wRequest);
            //根据链接显示内容,获取该连接
                WebLink wLink=wResponse.getLinkWith("返回");
        //获取该连接对应的href地址
            String actual=wLink.getURLString();
            //获取所期待的链接地址
            String expected="UserLogin.html";
           assertEquals(expected, actual);
        } catch (Exception e) {
            fail();
            } 
        }
}
原文地址:https://www.cnblogs.com/J-wym/p/3277187.html