1 JUnit的提出html
官网:http://junit.orgjava
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)的功能。eclipse
点击下载安装连接:工具
托管在GitHub中。测试
JUnit3中,全部须要测试的类直接继承junit.framework.TestCase类,便可用JUnit进行自动化测试。而在JUnit4中则没必要如此。htm
JUnit4文档:http://junit.org/junit4/javadoc/latest/index.htmlblog
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断言,效率大大提升,使用方式更加灵活,直观。