Junit单元测试

来源:互联网 发布:Ubuntu 软件怎么打不开 编辑:程序博客网 时间:2024/05/01 08:00
 

Junit4最大的亮点就是引入了注解(annotation),通过解析注解就可以为测试提供相应的信息,抛弃junit3使用命名约束以及反射机制的方法。

/**

 * 被测试类

 */

package com.stock.finance.service;

 

import java.util.List;

import java.util.zip.DataFormatException;

import com.stock.finance.db.dao.TableCompanyDAO;

import com.stock.finance.db.model.TableCompany;

 

/**

*

 */

public class CompanyService {

    private TableCompanyDAO dao = new TableCompanyDAO();

   

    public CompanyService(){

    }

    /**

     * @param code

     * @param name

     * @param masterBusiness

     */

    public void insert(String code,String name,String masterBusiness){

        TableCompany company = new TableCompany(code, name);

        company.setMasterBusiness(masterBusiness);

        insert(company);

    }

    /**

     * @param company

     */

    public void insert(TableCompany company){

        dao.save(company);

    }

    /**

     * @return

     */

    public int companyNum(){

        List<?> list = dao.findAll();

        return list.size();

    }

   

    public void justForDisplay() throws DataFormatException{

        throw new DataFormatException();

    }

}

/**

 * junit3测试类

 */

package test.com.stock.finance.service;

import java.util.zip.DataFormatException;

import com.stock.finance.service.CompanyService;

import junit.framework.TestCase;

/**

 */

public class Tester3 extends TestCase {

         private CompanyService service = new CompanyService();

         protected void setUp() throws Exception {

                   super.setUp();

         }

         protected void tearDown() throws Exception {

                   super.tearDown();

         }

         public final void testInsertStringStringString() {

                   fail("Not yet implemented"); // TODO

         }

         public final void testInsertTableCompany() {

                   fail("Not yet implemented"); // TODO

         }

         public final void testCompanyNum() {

                   fail("Not yet implemented"); // TODO

         }

         public final void testJustForDisplay() {

                   try {

                            service.justForDisplay();

                   } catch (DataFormatException e) {

                            assertTrue("捕获异常正确", true);

                   }

         }

}

/**

 * junit4测试类

 */

package test.com.stock.finance.service;

//静态引用

import static org.junit.Assert.*;

 

import java.util.zip.DataFormatException;

 

import org.junit.After;

import org.junit.AfterClass;

import org.junit.Before;

import org.junit.BeforeClass;

import org.junit.Ignore;

import org.junit.Test;

 

import com.stock.finance.service.CompanyService;

 

/**

*

 */

public class Tester4 {

         private CompanyService service = new CompanyService();

         /**

          * @throws java.lang.Exception

          */

         @BeforeClass

         public static void setUpBeforeClass() throws Exception {

         }

         /**

          * @throws java.lang.Exception

          */

         @AfterClass

         public static void tearDownAfterClass() throws Exception {

         }

         /**

          * @throws java.lang.Exception

          */

         @Before

         public void setUp() throws Exception {

         }

         /**

          * @throws java.lang.Exception

          */

         @After

         public void tearDown() throws Exception {

         }

         @Test

         @Ignore

         public final void testInsertStringStringString() {

//               fail("Not yet implemented"); // TODO

         }

         @Test(timeout = 1000)

         public final void testInsertTableCompany() {

//               fail("Not yet implemented"); // TODO

         }

         @Test

         public final void testCompanyNum() {

                   fail("Not yet implemented"); // TODO

         }

         @Test(expected = DataFormatException.class)

         public final void testJustForDisplay() throws DataFormatException {

                   service.justForDisplay();

         }

}

junit3和junit4的使用区别如下
1.
JUnit3中需要继承TestCase类,但在JUnit4中已经不需要继承TestCase
2.JUnit3中需要覆盖TestCase中的setUptearDown方法,其中setUp方法会在测试执行前被调用以完成初始化工作,而tearDown方法则在结束测试结果时被调用,用于释放测试使用中的资源,而在JUnit4中,只需要在方法前加上@Before@After 
3.JUnit3中对某个方法进行测试时,测试方法的命令是固定的,例如对addBook这个方法进行测试,需要编写名字为tetAddBook的测试方法,而在JUnit4中没有方法命令的约束,在方法的前面加上@Test,这就代表这个方法是测试用例中的测试方法
4.新的断言assertThat 
5.
 @BeforeClass 和 @AfterClass 。在JUnit3,如果所有的test case仅调用一次setUp()和tearDown()需要使用TestSetup类
6.测试异常处理@Test(expected = DataFormatException.class)
7.设置超时@Test(timeout = 1000)
8.忽略测试@Ignore
9.集成测试

 

 

集成测试

    利用TestSuite可以将一个TestCase子类中所有test***()方法包含进来一起运行,还可将TestSuite子类也包含进来,从而行成了一种等级关系。可以把TestSuite视为一个容器,可以盛放TestCase中的test***()方法,它自己也可以嵌套。这种体系架构,非常类似于现实中程序一步步开发一步步集成的现况。

    在junit中,Test、TestCase和TestSuite三者组成了composiste pattern。通过组装自己的TestSuite,可以完成对添加到这个TestSuite中的所有的TestCase的调用。而且这些定义的TestSuite还可以组装成更大的TestSuite,这样同时也方便了对于不断增加的TestCase的管理和维护。

    它的另一个好处就是,可以从这个TestCase树的任意一个节点(TestSuite或TestCase)开始调用,来完成这个节点以下的所有TestCase的调用。提高了unit test的灵活性。

例如:

### JUnit-3.8.1结构:

import junit.framework.Test;

import junit.framework.TestSuite;

public class TestAll{

    //定义一个suite,对于junit的作用可以视为类似于java应用程序的main。

    public static Test suite(){

        TestSuite suite = new TestSuite("Running all tests.");

        suite.addTestSuite( TestCase1.class);

        suite.addTestSuite( TestCase2.class);

        return suite;

    }

}

### JUnit-4.X结构:

import org.junit.runner.RunWith;

import org.junit.runners.Suite;

@RunWith(Suite.class)

@Suite.SuiteClasses({ TestCase1.class, TestCase2.class })

public class AllCalculatorTests {

 

}

//代码示例:在junit3中如何通过执行多个测试方法,却只执行一次setUp,tearDown方法

import junit.framework.*;
import junit.extensions.TestSetup;
public class AllTestsOneTimeSetup {
    public static Test suite() {
        TestSuite suite = new TestSuite();
        suite.addTest(SomeTest.suite());
        suite.addTest(AnotherTest.suite());
        TestSetup wrapper = new TestSetup(suite) {
            protected void setUp() {
                oneTimeSetUp();
            }
            protected void tearDown() {
                oneTimeTearDown();
            }
        };
        return wrapper;
    }
    public static void oneTimeSetUp() {
        // one-time initialization code
    }
    public static void oneTimeTearDown() {
        // one-time cleanup code
    }
}

 

我个人认为, JUnit4最大的特点是引入了Java5的注释Annotation。
1. @Test
    在JUnit3,所有的test case的方法名都要以"test"为前缀prefix;
    在JUnit4,在test case的方法前加上@Test,就明白了。
@Test 
public void empty() {         
        /* test case 1*/          
        Collection collection = new ArrarList();         
        assertTrue(collection.isEmpty());         
}
 
2. @Before 和 @After
    @Before 和 @After 就是setUp()和tearDown()的替代。
@Before     
public void runBeforeEveryTest() {        
        simpleMath = new SimpleMath();        
}        
     
@After     
public void runAfterEveryTest() {        
        simpleMath = null ;        
}
 
3. @BeforeClass 和 @AfterClass
    在JUnit3,如果想仅调用一次setUp()和tearDown()  for  all test cases, 使用TestSetup类;在JUnit4,就省事了:
@BeforeClass     
public static void runBeforeClass() {        
        // run for one time before all test cases         
}        
     
@AfterClass     
public static void runAfterClass() {        
        // run for one time after all test cases         
}
 
4. 测试异常处理
    在《JUnit3的使用 》文章中,看到旧式的异常测试是在抛出异常的代码中放入 try 块,然后在 try 块的末尾加入一个 fail() 语句:
public void testCase2() {         
        /* test case 2*/          
        ArrayList emptyList = new ArrayList();    
        try {    
                Object o = emptyList.get(0);    
                fail("Should raise an IndexOutOfBoundsException" );    
        } catch (IndexOutOfBoundsException expected) {    
                assertTrue(true );    
        }    
}
     在JUnit4,添加@Test,使用参数“expected”,并指明抛出异常的Exception类:
@Test(expected = IndexOutOfBoundsException.class ) 
public void testCase2() {         
        /* test case 2*/          
        ArrayList emptyList = new ArrayList();    
        Object o = emptyList.get(0);    
}
 
5. @Ignore
     对于你想暂时不进行的test cse, 在该方法前添加@Ignore
@Ignore("Not Ready to Run" )        
@Test     
public void multiplication() {        
        assertEquals(15, simpleMath.multiply(3, 5));        
}
 
6. 设置超时
    在@Test,使用"timeout"参数。如果测试运行的时间超过指定的毫秒数,则测试失败。
@Test(timeout=3000) 
public void remoteBaseRelativeResolutionWithDirectory()    
 throws IOException, ParsingException { 
  readBuilder.parse("config.xml" );    
}
 
7.添加了新的断言
      JUnit 4 为比较数组添加了两个 assert() 方法:
  public static void assertEquals(Object[] expected, Object[] actual)
      public static void assertEquals(String message, Object[] expected, Object[] actual)
  这两个方法以最直接的方式比较数组:如果数组长度相同,且每个对应的元素相同,则两个数组相等,否则不相等。数组为空的情况也作了考虑。
@Test     
public void listEquality() {        
        List<Integer> expected = new ArrayList<Integer>();        
        expected.add(5);        
     
        List<Integer> actual = new ArrayList<Integer>();        
        actual.add(5);        
     
        assertEquals(expected, actual);        
}
 
8. JUnit4Adapter
     为了能够在JUnit3环境下run JUnit4  test, 所以提供了JUnit4Adapter
public static junit.framework.Test suite() {        
        return new JUnit4TestAdapter(SimpleMathTest.class );        
}
 
9.其他
 失败(assert 方法检测到的预期的错误)与错误(异常指出的非预期的错误)之间不再有任何差别。尽管 JUnit 3 测试运行程序仍然可以区别这些情况,而 JUnit 4 运行程序将不再能够区分。

二、运行原理:

JUnit运行时都是由一个runner运行的。你可以根据需要选择不同的Runner来运行你的测试代码。指定一个Runner,需要使用@RunWith标注,并且把你所指定的Runner作为参数传递给它。系统自动使用默认Runner TestClassRunner 来运行你的代码。如下:

@RunWith (TestClassRunner.class)

public class JavaTest { …… }

 

JUnit4提出了"参数化测试 "的概念,只写一个测试函数,把这若干种情况作为参数传递进去,一次性的完成测试。代码如下:

 

@RunWith(Parameterized.class)
public class JavaTest {
private int param;
private int param2;
private int result;

 @Parameters public static Collection data() {
return Arrays.asList(new Object[][]{ { 2, 4, 6 }, { 0, 0, 0 }, { -3, 9, 6 } });
}

 // 构造函数,对变量进行初始化
public JavaTest(int param, int param2, int result) {
this.param = param;
this.param2 = param2;
this.result = result;
}

@Test public void run() {
//do some thing use args, and assert it
int expected = param + param2;
assertEquals(expected, result);
}
@Ignore("lala") public void lala() {
assertEquals(3,3);
}


首先,你要为这种测试专门生成一个新的类,为这个类指定一个Runner,特殊的功能要用特殊的Runner:@RunWith(Parameterized.class) 

第二步,定义测试数据的集合,也就是上述的data()方法,该方法可以任意命名,但是必须使用@Parameters标注进行修饰。这是一个二维数组,每组数据产生一个测试Instance.
第三步,构造函数,取得传过来的参数。
最后,用取得的参数做测试。@Test public void …

 

三、打包测试:

采取分而治之的方法,我们可以写多个类来降低测试难度。我们有时也希望一次把所有测试跑一遍,这时我们写一个打包类

import junit.framework.JUnit4TestAdapter;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;

 

@RunWith(Suite.class)
@Suite.SuiteClasses({
JavaTest.class,
JustDo.class
})
public class TestAll {
}

 

四、多线程测试

      JUnit4的Test写好以后,对于一些集成度比较高的测试用例,还希望完成并发访问情况下的测试,但是,JUnit4缺省情况没有提供,我希望通过自 己写一个main函数,然后创建几个线程,在几个线程中同时运行测试用例进行测试,来模拟并发访问的情况,下里为具体例子:

public class TestExample {

@Test
public void testMethod() {
System.out.println("test success!");
}
}

public class PerfomanceTest {

public static void main(String[] args) {
new Thread() {public void run() {
 
// JUnitCore.runClasses(new Class[] { TestExample .class });            (1) 
// new JUnitCore().run(Request.method(TestExample .class, "testMethod "));        (2) 
}}.start();
}
}
 
注:标志1或标志2中只要用一种就可以测试。

到这里,我们就可以使用JUnit4来开发我们自己的测试了。

编译和运行JUnit 
在JUnit3中提供了三种运行界面:
TestUI:Provides text-based output to stdout
AwtUI: Provides GUI-based output using the AWT(Abstract Window Toolkit)from Java
SwingUI: Provides GUI-based output using the Swing graphical user interface component kit from Java.

设置好环境变量后,在命令行运行:
java junit.USERINTERFACE.TestRunner classfile

例如:
java junit.testui.TestRunner BaseClassTest

在JUnit4中,只有标准输出界面,使用org.junit.runner.JUnitCore类来运行:
java org.junit.runner.JUnieCore BaseClassTest




转自:点击打开链接

0 0
原创粉丝点击