代码改变世界

单元测试

2016-09-11 00:07  李秀琪  阅读(215)  评论(0编辑  收藏  举报

1什么是单元测试?

单元测试(junit testing),是指对软件中的最小可测试单元进行检查和验证。Java里单元指一个类。

JUnit ,是一个开源的Java单元测试框架,是 Java的标准单元测试库,是非常重要第三方 Java 库,由 Kent Beck 和 Erich Gamma 开发。

Junit作为一个软件测试的工具,JUnit可以不破坏java原代码,使用方便,添加快捷,代码量少,可视化的测试。

2:JUnit单元测试步骤:

1.导入包junit测试包:JUnit测试版本,3.81版,4.0版,导入对应的jar包;

2.写一个类扩展(继承)TestCase;

3.在需要测试的方法名前加test生成新的测试方法;
4.运行测试,用断言(assert***)的方法测试成功(显示绿色)或失败(显示红色),或者自己判断结果正确与否。

 

junit类单元测试:

  1. package com.myhome;  
  2.   
  3. public class Mul{  
  4. public int mul(int x,int y) {  
  5.     public int mul(int x,int y) {  
  6.         return x*y;  
  7.     }  
  8.     public double divide(double x,double y){  
  9.         return x/y;  
  10.     }  
  11. }  

 

用myeclipse集成开发环境添加jar包和junit测试支持:

 

 

 

1.如果没有就在new菜单最下边Other……中(或Ctrl+N),输入junit选择JUnit Test Case单元测试:

 

 

2.选择JUnit 3 Test测试:

 

 

3.选择要测试的方法:

 

 

4.此时会自动导入jar包(junit3或者junit4需要的jar包),

5.程序目录结构:

 

 

6.此时的测试类为:

  1. package com.myhome.test;  
  2.   
  3. import junit.framework.TestCase;  
  4.   
  5. public class MulTest extends TestCase {  
  6.   
  7.     public void testMul() {  
  8.         fail("Not yet implemented");  
  9.     }  
  10.   
  11.     public void testDivide() {  
  12.         fail("Not yet implemented");  
  13.     }  
  14.   
  15. }  

 

测试内部方法体:

  1. public void testMul() {  
  2.     Mul mul = new Mul();  
  3.     int res = mul.mul(2, 4);  
  4.     System.out.println(res);  
  5. }  
  6.   
  7. public void testDivide() {  
  8.     Mul mul = new Mul();  
  9.     double res = mul.divide(8.0, 2.0);  
  10.     assertEquals(4.0, res);  
  11. }  

 

效果图: