junit4单元测试总结

来源:互联网 发布:js权威指南第六版 pdf 编辑:程序博客网 时间:2024/06/05 09:33

junit4单元测试总结

本文开发环境为myeclipse10.7

1.  准备工作

1.1. 选择需要单元测试的文件

创建maven工程,右击需要单元测试的文件,选择New->other,选择Junit Test Case;

1.2. 选择Junit 4

代码放到src/test/java

1.3. 选择单元测试函数

添加Junit 4 引用

1.4. 生成test文件

2.  开始测试

2.1. 测试单个函数

方法1:鼠标选到带测试函数名上,右击,Run As Junit Test;

方法2:在Junit View里选择要测试的函数,右击Run;

2.2. 测试整个类

方法1:鼠标选到类上,右击,Run As Junit Test;

方法2:在Junit View里选择要测试的类,右击Run;

 

3.  常用技巧

3.1. 常用注解

在junit中常用的注解有@Test、@Ignore、@BeforeClass、@AfterClass、@Before、@After、@Runwith、@Parameters

JUnit4的测试类不用再继承TestCase类了。使用注解会方便很多。

@Before

初始化方法

@After

释放资源

@Test

测试方法,在这里可以测试期望异常和超时时间

@Ignore

忽略的测试方法

@BeforeClass

针对所有测试,只执行一次,且必须为static void

@AfterClass

针对所有测试,只执行一次,且必须为static void

@RunWith

指定测试类使用某个运行器

@Parameters

指定测试类的测试数据集合

@Rule

允许灵活添加或重新定义测试类中的每个测试方法的行为

@FixMethodOrder

指定测试方法的执行顺序

一个JUnit 4 的单元测试用例执行顺序为:
@BeforeClass –> @Before –> @Test –> @After –> @AfterClass
每一个测试方法的调用顺序为:
@Before –> @Test –> @After

3.1.1.  @Test

@Test注解的publicvoid方法将会被当做测试用例

JUnit每次都会创建一个新的测试实例,然后调用@Test注解方法

任何异常的抛出都会认为测试失败

@Test注解提供2个参数:

1,“expected”,定义测试方法应该抛出的异常,如果测试方法没有抛出异常或者抛出了一个不同的异常,测试失败

2,“timeout”,如果测试运行时间长于该定义时间,测试失败(单位为毫秒)

[java] view plaincopy

1.  public class MathTest {  

2.     @Test(expected=Exception.class)  

3.      public void testAdd() throws Exception{  

4.         throw new Exception();  

5.      }  

6. }  

[java] view plaincopy

1.  public class MathTest {  

2.     @Test(timeout=5000)  

3.      public void testAdd() {  

4.         for(;;){  

5.                

6.         }  

7.      }  

8. }  

3.1.2.  @Before

当编写测试方法时,经常会发现一些方法在执行前需要创建相同的对象

使用@Before注解一个publicvoid 方法会使该方法在@Test注解方法被执行前执行(那么就可以在该方法中创建相同的对象)

父类的@Before注解方法会在子类的@Before注解方法执行前执行

3.1.3.  @After

如果在@Before注解方法中分配了额外的资源,那么在测试执行完后,需要释放分配的资源。

使用@After注解一个publicvoid方法会使该方法在@Test注解方法执行后被执行

即使在@Before注解方法、@Test注解方法中抛出了异常,所有的@After注解方法依然会被执行,见示例

父类中的@After注解方法会在子类@After注解方法执行后被执行

3.1.4.  @BeforeClass

有些时候,一些测试需要共享代价高昂的步骤(如数据库登录),这会破坏测试独立性,通常是需要优化的

使用@BeforeClass注解一个publicstatic void 方法,并且该方法不带任何参数,会使该方法在所有测试方法被执行前执行一次,并且只执行一次

父类的@BeforeClass注解方法会在子类的@BeforeClass注解方法执行前执行

3.1.5.  @AfterClass

如果在@BeforeClass注解方法中分配了代价高昂的额外的资源,那么在测试类中的所有测试方法执行完后,需要释放分配的资源。

使用@AfterClass注解一个publicstatic void方法会使该方法在测试类中的所有测试方法执行完后被执行

即使在@BeforeClass注解方法中抛出了异常,所有的@AfterClass注解方法依然会被执行

父类中的@AfterClass注解方法会在子类@AfterClass注解方法执行后被执行

3.1.6.  @Ignore

对包含测试类的类或@Test注解方法使用@Ignore注解将使被注解的类或方法不会被当做测试执行

JUnit执行结果中会报告被忽略的测试数

[java] view plaincopy

1.  public class MathTest {  

2.     @Ignore("do not test")  

3.      @Test  

4.     public void testAdd() {  

5.          Math m = new Math();  

6.         assertTrue(m.add(11) == 2);  

7.      }  

8. }  

[java] view plaincopy

1.  @Ignore  

2. public class MathTest {  

3.      @Test  

4.     public void testAdd() {  

5.          Math m = new Math();  

6.         assertTrue(m.add(11) == 2);  

7.      }  

8. }  

执行结果相同:

 

3.2. 制定执行顺序

JUnit4.11之后提供了MethodSorters,可以有三种方式对test执行顺序进行指定,如下:

    /**

     * Sorts the test methods by the methodname, in lexicographic order, with {@link Method#toString()} used as a tiebreaker

     */

    NAME_ASCENDING(MethodSorter.NAME_ASCENDING),

 

    /**

     * Leaves the test methods in the orderreturned by the JVM. Note that the order from the JVM may vary from run to run

     */

    JVM(null),

 

    /**

     * Sorts the test methods in adeterministic, but not predictable, order

     */

    DEFAULT(MethodSorter.DEFAULT);

可以小试牛刀一下:

3.2.1.  使用DEFAULT方式

默认使用一个确定的,但不可预测的顺序

package com.netease.test.junit;

 

import org.apache.log4j.Logger;

import org.junit.FixMethodOrder;

import org.junit.Test;

import org.junit.runners.MethodSorters;

 

/**

 * User: hzwangxx

 * Date: 14-3-31

 * Time: 15:35

 */

@FixMethodOrder(MethodSorters.DEFAULT)

publicclass TestOrder {

    private static final Logger LOG = Logger.getLogger(TestOrder.class);

    @Test

    public void testFirst() throws Exception{

        LOG.info("------1--------");

    }

 

    @Test

    public void testSecond() throwsException {

        LOG.info("------2--------");

 

    }

 

    @Test

    public void testThird() throwsException {

        LOG.info("------3--------");

    }

 

}

/*

output:

2014-03-3116:04:15,984 0    [main] INFO  - ------1--------

2014-03-3116:04:15,986 2    [main] INFO  - ------3--------

2014-03-3116:04:15,987 3    [main] INFO  - ------2--------

*/

3.2.2.  按字母排序

根据测试方法的方法名排序,按照词典排序规则(ASC,从小到大,递增)

package com.netease.test.junit;

 

import org.apache.log4j.Logger;

import org.junit.FixMethodOrder;

import org.junit.Test;

import org.junit.runners.MethodSorters;

 

/**

 * User: hzwangxx

 * Date: 14-3-31

 * Time: 15:35

 */

@FixMethodOrder(MethodSorters.NAME_ASCENDING)

publicclass TestOrder {

    private static final Logger LOG = Logger.getLogger(TestOrder.class);

    @Test

    public void testFirst() throwsException {

        LOG.info("------1--------");

    }

 

    @Test

    public void testSecond() throwsException {

        LOG.info("------2--------");

 

    }

 

    @Test

    public void testThird() throws Exception{

        LOG.info("------3--------");

    }

 

}

/*

2014-03-3116:10:25,360 0    [main] INFO  - ------1--------

2014-03-3116:10:25,361 1    [main] INFO  - ------2--------

2014-03-3116:10:25,362 2    [main] INFO  - ------3--------

*/

3.3. 常用断言

断言是编写测试用例的核心实现方式,即期望值是多少,测试的结果是多少,以此来判断测试是否通过。

assertArrayEquals(expecteds, actuals)

查看两个数组是否相等。

assertEquals(expected, actual)

查看两个对象是否相等。类似于字符串比较使用的equals()方法

assertNotEquals(first, second)

查看两个对象是否不相等。

assertNull(object)

查看对象是否为空。

assertNotNull(object)

查看对象是否不为空。

assertSame(expected, actual)

查看两个对象的引用是否相等。类似于使用“==”比较两个对象

assertNotSame(unexpected, actual)

查看两个对象的引用是否不相等。类似于使用“!=”比较两个对象

assertTrue(condition)

查看运行结果是否为true。

assertFalse(condition)

查看运行结果是否为false。

assertThat(actual, matcher)

查看实际值是否满足指定的条件

fail()

让测试失败

 

4.  常见问题

4.1. java.lang.ClassNotFoundException

右击项目,Run As Maven Test,等待test完成就不报该错误了。

 

0 0
原创粉丝点击