zoukankan      html  css  js  c++  java
  • junit4单元測试总结

    junit4单元測试总结

    本文开发环境为myeclipse10.7

    1.  准备工作

    1.1. 选择须要单元測试的文件

    创建mavenproject。右击须要单元測试的文件,选择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)

    public class 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)

    public class 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完毕就不报该错误了。

  • 相关阅读:
    FFmpeg 协议初步学习
    HTML DOM(一):认识DOM
    ant 安装
    ubunut 查看port被哪个程序占用
    cacti气象图调整(批量位置调整、更改生成图大小等)
    内网port映射具体解释(花生壳)
    HDU 2647 Reward(图论-拓扑排序)
    白话经典算法系列之七 堆与堆排序
    Codeforces Round #191 (Div. 2)---A. Flipping Game
    Serverlet具体解释
  • 原文地址:https://www.cnblogs.com/mfmdaoyou/p/6746208.html
Copyright © 2011-2022 走看看