zoukankan      html  css  js  c++  java
  • JUnit测试框架的使用

    1、学习Junit框架的使用

    可通过以下两个示例进行学习。

    A、Junit使用方法示例1

    1)把Junit引入当前项目库中

    新建一个 Java 工程—coolJUnit,打开项目coolJUnit 的属性页 -> 选择“Java Build Path”子选项 -> 点选“Add Library…”按钮 -> 在弹出的“Add Library”对话框中选择 JUnit(图1),并在下一页中选择版本 Junit 4 后点击“Finish”按钮。这样便把 JUnit 引入到当前项目库中了。

    2)新建单元测试代码目录

    单元测试代码是不会出现在最终软件产品中的,所以最好为单元测试代码与被测试代码创建单独的目录,并保证测试代码和被测试代码使用相同的包名。这样既保证了代码的分离,同时还保证了查找的方便。遵照这条原则,在项目 coolJUnit 根目录下添加一个新目录 testsrc,并把它加入到项目源代码目录中。(见 图2、3)。

     

    3)在工程中添加类

    添加类SampleCaculator,类中有两个方法,分别计算加减法。编译代码。

    public class SampleCalculator {
    
        //计算两整数之和
        public int add(int augend, int addend){
            return augend + addend;
        }
    
        //计算两整数之差
        public int subtration(int minuend, int subtrahend){
            return minuend - subtrahend;
        }
    }
    

    4)写单元测试代码

    为类SampleCalculator添加测试用例。在资源管理器SampleCalculator.java文件处右击选new>选Junit Test Case(见图4),Source foler选择testsrc目录,点击next,选择要测试的方法,这里把add和subtration方法都选上,最后点finish完成。

     

    Junit自动生成测试类SampleCalculatorTest,修改其中的代码(如下)。

    其中assertEquals断言,用来测试预期目标和实际结果是否相等。

    assertEquals( [Sting message], expected, actual )

    expected是期望值(通常都是硬编码的),actual是被测试代码实际产生的值,message是一个可选的消息,如果提供的话,将会在发生错误时报告这个消息。

    如想用断言来比较浮点数(在Java中是类型为float或者double的数),则需指定一个额外的误差参数。

    assertEquals([Sting message], expected, actual, tolerance)

    其它断言参见课本和参考书介绍。测试方法需要按照一定的规范书写:

    1. 测试方法必须使用注解 org.junit.Test 修饰。

    2. 测试方法必须使用 public void 修饰,而且不能带有任何参数。

     

    5)查看运行结果

    在测试类上点击右键,在弹出菜单中选择 Run As JUnit Test。运行结果如下图,绿色的进度条提示我们,测试运行通过了。 

    B、Junit使用方法示例2

    1)在工程中添加类

    类WordDealUtil中的方法wordFormat4DB( )实现的功能见文件注释。

    import java.util.regex.Matcher;
    
    import java.util.regex.Pattern;
    
    public class WordDealUtil {
    
        /**
    
         * 将Java对象名称(每个单词的头字母大写)按照
    
         * 数据库命名的习惯进行格式化
    
         * 格式化后的数据为小写字母,并且使用下划线分割命名单词
    
         * 例如:employeeInfo 经过格式化之后变为 employee_info
    
         * @param name Java对象名称
    
         */
    
        public static String wordFormat4DB(String name){
    
            Pattern p = Pattern.compile("[A-Z]");
    
            Matcher m = p.matcher(name);
    
            StringBuffer strBuffer = new StringBuffer();
    
            while(m.find()){
                //将当前匹配子串替换为指定字符串,
                //并且将替换后的子串以及其之前到上次匹配子串之后的字符串段添加到一个StringBuffer对象里
                m.appendReplacement(strBuffer, "_"+m.group());
    
            }
    
            //将最后一次匹配工作后剩余的字符串添加到一个StringBuffer对象里
            return m.appendTail(strBuffer).toString().toLowerCase();
        }
    
    }
    

    2)写单元测试代码

    import static org.junit.Assert.*;
    import org.junit.Test;
    public class WordDealUtilTest {
    	
    	@Test
    	public void testWordFormat4DB() {
    		String target = "employeeInfo";
    		String result = WordDealUtil.wordFormat4DB(target);
    		assertEquals("employee_info", result);
    	}
    }
    

    3)进一步完善测试用例

    单元测试的范围要全面,如对边界值、正常值、错误值的测试。运用所学的测试用例的设计方法,如:等价类划分法、边界值分析法,对测试用例进行进一步完善。继续补充一些对特殊情况的测试:

    //测试 null 时的处理情况
    
        @Test public void wordFormat4DBNull(){
            String target = null;
            String result = WordDealUtil.wordFormat4DB(target);
            assertNull(result);
        }
    
        //测试空字符串的处理情况
        @Test public void wordFormat4DBEmpty(){
            String target = "";
            String result = WordDealUtil.wordFormat4DB(target);
            assertEquals("", result);
        }
    
        //测试当首字母大写时的情况
        @Test public void wordFormat4DBegin(){
            String target = "EmployeeInfo";
            String result = WordDealUtil.wordFormat4DB(target);
            assertEquals("employee_info", result);
        } 
    
        //测试当尾字母为大写时的情况
        @Test public void wordFormat4DBEnd(){
            String target = "employeeInfoA";
            String result = WordDealUtil.wordFormat4DB(target);
            assertEquals("employee_info_a", result);
        }
    
        //测试多个相连字母大写时的情况
        @Test public void wordFormat4DBTogether(){
            String target = "employeeAInfo";
            String result = WordDealUtil.wordFormat4DB(target);
            assertEquals("employee_a_info", result);
        }
    

    4)查看分析运行结果,修改错误代码

    再次运行测试。JUnit 运行界面提示我们有两个测试情况未通过测试(见图6),当首字母大写时得到的处理结果与预期的有偏差,造成测试失败(failure);而当测试对 null 的处理结果时,则直接抛出了异常——测试错误(error)。显然,被测试代码中并没有对首字母大写和 null 这两种特殊情况进行处理,修改如下:

    //修改后的方法wordFormat4DB

             public static String wordFormat4DB(String name){
                      if(name == null){
                               return null;
                      }
                      Pattern p = Pattern.compile("[A-Z]");
                      Matcher m = p.matcher(name);
                      StringBuffer sb = new StringBuffer();               
                      while(m.find()){
                               if(m.start() != 0)
                                        m.appendReplacement(sb, ("_"+m.group()).toLowerCase());
                      }
                      return m.appendTail(sb).toString().toLowerCase();
             }
    

    2、使用Junit框架对类Date和类DateUtil(参见附录)进行单元测试。

    只对包含业务逻辑的方法进行测试,包括:

    类Date中的

    isDayValid(int year, int month, int day)

    isMonthValid(int month)

    isYearValid(int year)

    类DateUtil中的

    isLeapYear(int year)

    getDayofYear(Date date)

  • 相关阅读:
    VFL使用
    深复制与浅复制&&strong,copy修饰符总结
    数组的三种查找方法
    开发技巧-代码块使用
    2 duplicate symbols for architecture“文件冲突”
    利用echarts画折线图圆饼
    tab栏切换2
    利用highcharts.js画圆饼
    tab切换
    file上传图片并展示
  • 原文地址:https://www.cnblogs.com/hehaiyang/p/4069997.html
Copyright © 2011-2022 走看看