Junit的概念

author: scruffybear

release time: 04/01/2007

company: Watchdata  

如有转载,请注明出处,并保持文章的完整性,谢谢!  

    JUnit就是对程序代码进行单元测试的一种Java框架。实际上是一个Java类包可以用来编写自动化测试工具,这样就可以运行程序进行反复测试,减少测试的难度以及减少编写程序的错误。有了这个工具,在了解程序的外部特性的情况下,就可以在编写程序之前就可以进行编写测试工具,与发同时进行。仅用一个小例子来说明:

   首先下载一个Junit包,可以到其官方网站上去下载http://www.junit.org/index.htm,

   由于这里下载太慢,我是在baidu里输入junit.jar来搜索找到的。

   编写一个简单的类Car.java
   内容为:
    public class Car
   {  
    public int getWheels(){
    return 4;
    }
   }

编写Junit测试程序,文件名为testCar.java,内容为:
//执行测试的类(JUnit版)
import junit.framework.*;

public class testCar extends TestCase
{
    protected int expectedWheels;
    protected Car myCar;

    public testCar(String name)
      {
         super(name);
      }


    protected void setUp()
      {
         expectedWheels = 4;
         myCar = new Car();
      }


    public static Test suite()
      {
        /** the type safe way */
    
       TestSuite suite= new TestSuite();
       suite.addTest(
               new testCar("Car.getWheels")
                         {
                            protected void runTest()
                              {
                                 testGetWheels();
                              }
                          }
                     );
       return suite;
      
     /** the dynamic way */
     //return new TestSuite(testCar.class);
      }

     public void testGetWheels()
      {
        assertEqual*(expectedWheels , myCar.getWheels());
      }
}

最后就可以对所编写的Car类进行测试了。在命令行中输入以下命令:
D:/thinking in java/eclipse/thinkinginjava>java junit.textui.TestRunner

testCar
.
Time: 0

OK (1 test)

如果把expectedWheel*的值改动为不是4,例如改为**pectedWheels = 3; 再进行测试:
如果如下:
D:/thinking in java/eclipse/thinkinginjava>java junit.textui.TestRunner

testCar
.F
Time: 0
There was 1 failure:
1) Car.getWheels(testCar$1)junit.framework.AssertionFailedError: expected:<3>

but was:<4>
        at testCar.testGetWheels(testCar.java:44)
        at testCar$1.runTest(testCar.java:32)

FAILURES!!!
Tests run: 1,  Failures: 1,  Errors: 0
  在“.”后有一个F,表明有一个错误。接着说明是在Car.getWheels方法出错,并详细说明了是哪里出错。
  这是网上一个经典的案例,我只不过是重新照着做了一遍。在网上搜索“JUnit实战”即可搜到。
  
  没有进行深入研究,网上有很多文章,列几个:


http://dev.csdn.net/develop/article/50/article/51/51184.shtm
http://hedong.3322.org/archives/000224.html
http://blog.csdn.net/rosen/archive/2004/07/11/39055.aspx
http://www.cn-java.com/index_download_center.php

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值