zoukankan      html  css  js  c++  java
  • JUnit使用

    1 JUnit的提出

    官网:http://junit.org

    JUnit is a simple framework to write repeatable tests. It is an instance of the xUnit architecture for unit testing frameworks.

    其中xUnit是一套基于测试驱动开发的测试框架,包含PythonUnit,CppUnit,JUnit。

    JUnit是由Erich Gamma和Kent Beck编写的一个回归测试框架。JUnit测试是程序员测试,即白盒测试,因为程序员知道被测试的软件如何(How)完成功能和完成什么样(What)的功能。


    点击下载安装链接:


    托管在GitHub中。

    JUnit3中,所有需要测试的类直接继承junit.framework.TestCase类,即可用JUnit进行自动化测试。而在JUnit4中则不必如此。

    JUnit4文档:http://junit.org/junit4/javadoc/latest/index.html

    JUnit是一个开发源代码的Java测试框架,用于编写和运行可重复的测试。在eclipse中已经集成好了此项工具。

    2 JUnit的基本使用

    以下是一个使用例子。

    MyMath.java

    package test;
    
    public class MyMath {
    	public int div(int i,int j) throws Exception{	// 定义除法操作,如果有异常,则交给被调用处处理
    		int temp = 0 ;	// 定义局部变量
    		temp = i / j ;	// 计算,但是此处有可能出现异常
    		return temp ;
    	}
    }
    

    右键选中src中的MyMath.java文件,new -> Other -> Java -> junit -> TestCase


     一般来说,一个测试用例对应着一个测试功能,一个测试站点对应着一套测试用例。点击next ,选择要测试的方法。



    选择Finish后,提示是否增加JUnit的包,点击OK。全部完成后会建立一个MyMathTest的类,代码如下:

    package test;
    
    import static org.junit.Assert.*;
    
    import org.junit.Test;
    
    public class MyMathTest {
    
    	@Test
    	public void testDiv() {
    		fail("Not yet implemented");
    	}
    
    }
    

    修改MyMathTest类。

    package test;
    
    import static org.junit.Assert.*;
    
    import org.junit.Test;
    
    import junit.framework.Assert;
    
    public class MyMathTest {
    
    	@Test
    	public void testDiv() {
    		try{
    			Assert.assertEquals(new MyMath().div(10, 2), 5);
    			Assert.assertEquals(new MyMath().div(10, 3), 3,1);
    		}catch(Exception e){
    			e.printStackTrace();
    		}
    	}
    }
    

    点击运行


     如果正确,则会显示Green Bar,否则,会显示Red Bar


    值得一提的是,try语句块内只要有错,Failures的数目都会为1.

    使用JUnit方式的最大好处是,相比自己使用assert断言,效率大大提高,使用方式更加灵活,直观。

  • 相关阅读:
    Best Cow Line(POJ No.3617)
    迷宫的最短路径
    Lak3 Counting(POJ No.2386)
    【日志】-2013.11.02
    用Python实现gmail邮箱服务,实现两个邮箱之间的绑定(上)
    用Python实现gmail邮箱服务,实现两个邮箱之间的绑定(下)
    【日志】-2013.11.01
    (转载)HTML与XHTML有什么区别
    (转载)linux环境变量
    转载-KMP算法前缀数组优雅实现
  • 原文地址:https://www.cnblogs.com/ioveNature/p/6536669.html
Copyright © 2011-2022 走看看