利用JUNIT进行单元测试 
杨恒贤([email protected]) 
  
1.  当进行单元测试时,我们应该利用回归测试方法。 
2.  Junit测试是程序员测试,即所谓白盒测试,因为程序员知道被测试的软件如何(How)完成功能和完成什么样(What)的功能。 
3.  Junit本质上是一套框架,即开发者制定了一套条条框框,遵循这此条条框框要求编写测试代码,如继承某个类,实现某个接口,就可以用Junit进行自动测试了。 
配置 
| 
 Eclipse2.11  | 
 ftp://192.168.213.48/yanghx_tools  |  
| 
 JUNIT3.81  | 
 ftp://192.168.213.48/yanghx_tools  |   
  
Eclipse2.11自带JUNIT插件,并且已经配置好了 
JUINT3.81配置 
测试 
1.    在环境变量上增加JUNIT_HOME,他的值就是JUNIT目录 
2.    在环境变量Path增加%JUNIT_HOME%\junit.jar 
3.    运行下面脚本 
  
set classpath=%java_home%\lib\tools.jar;%junit_home%;%junit_home%\junit.jar 
java junit.swingui.TestRunner junit.samples.AllTests 
pause 
  
出现这样的画面就说明JUNIT配置成功 
下面我们利用Eclipse2.11进行JUNIT测试案例设计 
我们作一个HelloWorld的测试 
测试方法: 
1.    HelloWorld.sayHello()是否执行正常,并且结果也符合要求 
2.    HelloWorld.add()方法是否与我们预期一样执行 
  
根据测试方案,我们编写测试案例 
  
  
  
  
  
/* 
 * Created on 2004-2-9 
 * 
 * To change the template for this generated file go to 
 * Window>Preferences>Java>Code Generation>Code and Comments 
 */ 
package com.yjsoft.app; 
  
/** 
 * @author yanghx2004 
 * 
 * To change the template for this generated type comment go to 
 * Window>Preferences>Java>Code Generation>Code and Comments 
 */ 
public class HelloWorld { 
  
    public static void main(String[] args) { 
    } 
    public String sayHello(){ 
       return "Hello world."; 
    } 
    public int add(int nA,int nB){ 
       return nA+nB; 
    } 
} 
  
  
  
  
  
开始为此编写TestCase 
1.    先设置属性,设置Libraries,将Junit.Jar加入 
  
2.    创建TestCase测试工程 
  
3.    创建测试案例类 
  
4.    选择要测试的方法 
  
5.    编写测试代码 
/* 
 * Created on 2004-2-9 
 * 
 * To change the template for this generated file go to 
 * Window>Preferences>Java>Code Generation>Code and Comments 
 */ 
package com.yjsoft.test; 
  
import junit.framework.Assert; 
import junit.framework.TestCase; 
import com.yjsoft.app.HelloWorld; 
  
/** 
 * @author yanghx2004 
 * 
 * To change the template for this generated type comment go to 
 * Window>Preferences>Java>Code Generation>Code and Comments 
 */ 
public class HelloWorldTest extends TestCase { 
    /** 
     * Constructor for HelloWorldTest. 
     * @param arg0 
     */ 
    public HelloWorldTest(String arg0) { 
       super(arg0); 
    } 
  
    public static void main(String[] args) { 
       junit.swingui.TestRunner.run(HelloWorldTest.class); 
    } 
    public void testSayHello() { 
       HelloWorld world=new HelloWorld(); 
       //Assert.assertNull(world); 
       assertEquals(world.sayHello(),"Hello World"); 
    } 
    public void testAdd() { 
       HelloWorld world=new HelloWorld(); 
       //Assert.assertNull(world); 
       Assert.assertEquals(world.add(1,2),3); 
    } 
} 
  
6.    测试 
  
发现失败,方法为sayHello(),看看具体信息“应为Hello word. 却发现 Hello World” 
修改测试函数 
assertEquals(world.sayHello(),"Hello world."); 
7.    测试,通过 
8.      
  
关于JUNIT简单使用就介绍这么多, 关于用JUNIT来模拟请求进行JSP测试,我下次讲解。这要涉及到HttpUnit单元。  
 
  |