junit基础

JUnit中常用的接口和类
1.Test接口:运行测试和收集测试结果;Test接口使用了Composite设计模式,是单独测试用例(TestCase),聚合测试模式(TestSuite)及测试扩展(TestDecorator)的共同接口。
主要方法:
countTestCases:统计TestCases 数目
run:运行测试并将结果返回到指定的TestResult 中

2. TestCase是Test接口的抽象实现,(不能被实例化,只能被继承)其构造函数Teste(string name)根据的测试名称name创建一个测试实例。

主要方法:
countTestCases:返回TestCase 数目,直接返回1
getName,返回TestCase 当前准备允许的测试方法的名称(私有属性fName)
run:运行TestCase,如果没有指定结果存储的TestResult,将调用createResu(lt
方法。注意,TestCase 与TestResult 会有互相调用。

3. Assert静态类——一系列断言方法的集合,包含了一组静态的测试方法,用于期望值和实际值比对是否正确,即测试失败

主要方法:

assert:保留(deprecated)方法,判断一个条件是否为真
assertTrue:assert 的替代方法,判断一个条件是否为真
assertEquals:用于判断实际值和期望值是否相同(Equals),可以是各种JAVA
对象。
assertNotNull:判断一个对象是否不为空
assertNull:判断一个对象是否为空
assertSame:判断实际值和期望值是否为同一个对象( ==),注意和assertEquals区分
failNotEquals:主要用于assertEquals 方法,调用fail 返回失败提示
failNotSame:主要用于assertSame 方法,调用fail 返回失败提示
4. TestSuite测试包类——多个测试的组合,负责组装多个Test Cases

主要方法:

addTest:增加一个TestSuit 的实例到fTests中。注意由于TestCase 的
实例化实际上只指定一个测试方法,即增加一个TestCase 的实例是注册了其中一
个测试方法,参看TestCase 类。如参数是一个TestSuite,则相当于增加了一个子
Suite.
addTestSuite:增加一个子Suite,实际效果同参数为TestSuite 的addTest。
countTestCases:返回Suite(包括子Suite)中的TestCase 实例(测试方法)数

run:运行测试,注意这里是运行fTests 中的所有测试,用了TestResult.
shouldStop 方法来判断是否终止运行。实际是调用了runTest
runTest:运行某一TestCase 或子Suite 的测试,注意使用了递归。如果参数test
是一个TestSuite,会再调用TestSuite.run
testAt:返回fTests 指定顺序的TestCase 或者TestSuite
testCount:返回fTests 大小,注意和countTestCases 的区别
tests:返回fTests 的内容
setName:设置名称
getName:增加名称
toString:
private
addTestMethod:增加一个测试方法(TestCase 实例)到fTests
exceptionToString:返回一个Throwable 中的提示信息
getConstructor:返回指定类的构造函数
isPublicTestMethod:判断一个方法是否是public 的测试方法,即一个函数是否
是public 的,同时是一个测试方法,测试方法参考下面的isTestMethod。
isTestMethod:判断一个方法是否是测试方法,既以”test”为前缀、没有参数及
返回值。
warning:增加一个错误提示Testcase到fTests中,注意这里也使用了Anonymous
Class。warning 使用主要考虑的往往在对TestSuite 进行操作的时候,不会因为有
错就终止操作,而是在run 的时候报告错误
5. TestResult结果类集合了任意测试累加结果主要方法:
addError:增加错误,注意这里错误应该指测试程序本身的错误或者被测试程
序错误,而不是测试失败
addFailure:增加一个测试失败,专用于AssertionFailedError 的处理
endTest:结束测试
startTest:开始测试
6. TestListener接口是个事件监听规约,可供TestRunner类使用。它通知listener的对象相关事件
7. TestFailure失败类是个“失败”状况的收集类,解释每次测试执行过程中出现的异常情况。其toString()方法返回“失败”状况的简要描述
2.3  命名和用法
     1.测试用例:

命名:

待测试类的名称+Test

如:待测试类:HelloWorld.java

测试类:HelloWorldTest.java

用法:

  A.继承自TestCase,

  B.以testXXX方法的形式包含一个或多个测试(XXX:待测试类中方法的名称)

  2.测试集合:

命名:

待测试类的名称+Test

如:测试类:PayByBankTest.java,PayByCardTest.java

组合测试类:TestAllPay.java
2.4  juit控制台

Runs:一共运行的TestCase数量

Error:由于编译错误或程序错误所导致的测试失败

Failures:junit发出的错误(比如:断言失败,等等)

Failure Trace:异常信息

2.5  例子
待测试的类:

helloWorld.java(日志打印):

import org.apache.commons.logging.Log;

import org.apache.commons.logging.LogFactory;

public class HelloWorld {

private static final Log log = LogFactory.getLog(HelloWorld.class);

public void print(){

   log.info("Hello world!");

}
}

CommonMethod.java(日期格式化):

import java.text.SimpleDateFormat;

import java.util.Date;

import org.apache.commons.logging.Log;

import org.apache.commons.logging.LogFactory;

public class CommonMethod{

    private static final Log log = LogFactory.getLog(CommonMethod.class);

    public CommonMethod(){}

    public static String fromDate(Date dObj, String format){

         if (dObj == null) return "";

         SimpleDateFormat f1;

         if (format.equals(""))format = "yyyy-MM-dd HH:mm";

         f1 = new SimpleDateFormat(format);

         try{

             return f1.format(dObj);

         }catch(Exception e){

             log.warn(e.getMessage(), e);

         }

         return null;

     }

}

XmlParse.java(xml解析):

import java.io.ByteArrayOutputStream;

import java.io.DataOutputStream;

import java.io.File;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.InputStream;

import java.io.StringReader;

import org.apache.commons.logging.Log;

import org.apache.commons.logging.LogFactory;

import org.dom4j.Document;

import org.dom4j.io.OutputFormat;

import org.dom4j.io.SAXReader;

import org.dom4j.io.XMLWriter;

public class XmlParse{

    private static final Log log = LogFactory.getLog(XmlParse.class);

    private XmlParse(){}

    public static Document loadXML(String xmlStr){

         Document result = null;

         try{

             SAXReader sax = new SAXReader();

             result = sax.read(new StringReader(xmlStr));

         }catch (Exception ex){

             log.info("Input XML String Err:" + ex.toString(), ex);

             throw new RuntimeException(ex);

         }

         return result;

    }    public static Document loadXML(String xmlStr, String encoding){

         Document result = null;

         try{

             SAXReader sax = new SAXReader();

             sax.setEncoding(encoding);

             result = sax.read(new StringReader(xmlStr));

         }catch (Exception ex){

             log.info("Input XML String Err:" + ex.toString(), ex);

             throw new RuntimeException(ex);
         }
         return result;
   }}

1.   TestCase用法:
CommonMethodTest:
import java.util.Date;
import junit.framework.Test;
import junit.framework.TestCase;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public class CommonMethodTest {
private static final Log log = LogFactory.getLog(CommonMethodTest.class);
public static Test suite(){
           TestCase testCase = new TestCase("common"){

           @Override
           protected void runTest() throws Throwable {
               String dateStr = CommonMethod.fromDate(new Date(),"yyyy-MM-dd");
               log.info(dateStr);
          }
      };
      log.info(testCase.getName());
      return testCase;
}}
HelloWorldTest.java:
import java.util.Date;
import junit.framework.Test;
import junit.framework.TestCase;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public class HelloWorldTest extends TestCase {
public void testPrint(){ 
   HelloWorld helloWorld = new HelloWorld();
   helloWorld.print();
}}

XmlParseTest.java:

import junit.framework.TestCase;

import org.dom4j.Document;

public class XmlParseTest extends TestCase {

private String xml;

@Override

/*

* 测试用例运行时需要加载的

* 构造xml,测试时要使用的测试数据

*/  

protected void setUp() throws Exception {

      StringBuffer stringBuffer = new StringBuffer();
      stringBuffer.append("<xml>");
      stringBuffer.append("<user>");
      stringBuffer.append("<userId>1</userId>");
      stringBuffer.append("<name>mz</name>");
      stringBuffer.append("</user>");
      stringBuffer.append("<user>");
      stringBuffer.append("<userId>2</userId>");
     stringBuffer.append("<name>sg</name>");
      stringBuffer.append("</user>");
      stringBuffer.append("</xml>");
      xml = stringBuffer.toString();
}
public void testLoadXMLString() {
      Document document = XmlParse.loadXML(xml);
      assertNotNull(document);
}
public void testLoadXMLStringString() {
      Document document = XmlParse.loadXML(xml,"GB2312");
      assertNotNull(document);}
}

2. TestSuite用法:
TestAll.java:
import junit.framework.Test;
import junit.framework.TestSuite;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public class TestAll{
private static final Log log = LogFactory.getLog(TestAll.class);
public static Test suite(){  //TestSuite 用于组合测试,必须要有这样一个静态方法。
  TestSuite suite = new TestSuite();
  suite.addTestSuite(XmlParseTest.class);
  suite.addTestSuite(HelloWorldTest.class);
  suite.addTest(CommonMethodTest.suite());
  log.info("组合测试");
  log.info("countTestCases:" + suite.countTestCases());;
 
return suite;
}
}

一些使用 JUnit经验

不要用TestCase的构造函数初始化,而要用setUp()和tearDown()方法。
不要依赖或假定测试运行的顺序,因为JUnit利用Vector保存测试方法。所以不同的平台会按不同的顺序从Vector中取出测试方法。
避免编写有副作用的TestCase。例如:如果随后的测试依赖于某些特定的交易数据,就不要提交交易数据。简单的回滚就可以了。
当继承一个测试类时,记得调用父类的setUp()和tearDown()方法。
将测试代码和工作代码放在一起,一边同步编译和更新。
测试类和测试方法应该有一致的命名方案。如在工作类名前加上test从而形成测试类名。
确保测试与时间无关,不要依赖使用过期的数据进行测试。导致在随后的维护过程中很难重现测试。
如果你编写的软件面向国际市场,编写测试时要考虑国际化的因素。不要仅用母语的Locale进行测试。
尽可能地利用JUnit提供地assert/fail方法以及异常处理的方法,可以使代码更为简洁。
测试要尽可能地小,执行速度快。
下面是一个模板,也是 初学可供参考的JUNIT模板


package junit.sineat.templet;
import java.util.Hashtable;
import junit.framework.Assert;
import junit.framework.TestCase;
import junit.framework.TestSuite;
public class JunitB extends TestCase...{
/** *//**定义你需要测试的类及用到的变量*****************************/
public Hashtable hasha=null;//
    public Hashtable hashb=null;
/** *//*******************************************************/
public JunitB(String name)...{
super(name);//创建子类       
    }
/** *//**用setUp进行初始化操作*/
protected void setUp() throws Exception ...{
super.setUp();
hasha =new Hashtable();//这里   
    }
/** *//**用tearDown来销毁所占用的资源*/
protected void tearDown() throws Exception ...{
super.tearDown();
//System.gc();
    }
/** *//**写一个测试方法断言期望的结果**/
public void testBodyStatus() ...{
//hasha =new Hashtable();//有此句后也可去掉setUp() tearDown()
        assertNotNull(hasha);
//hasha.put("0","let's try again");//test1.error版
        assertTrue(hasha.isEmpty());//期望为空       
    }
/** *//**再写一个测试方法断言期望的结果**/
public void testBodySame() ...{
//hashb=(Hashtable)hasha.clone();     //test2.error版
        hashb=hasha;                        //test2.OK 版
        Assert.assertSame(hasha,hashb);
}
/** *//**suite()方法,使用反射动态的创建一个包含所有的testXxxx方法的测试套件**/
public static TestSuite suite()  ...{
return new TestSuite(JunitB.class);
}
/** *//****写一个main()运行测试*****************/
public static void main(String args[]) ...{
junit.textui.TestRunner.run(suite());//以文本运行器的方式方便的
//junit.swingui.TestRunner.run(JunitB.class);
    }
}

猜你喜欢

转载自bwj.iteye.com/blog/611495