分类: 电脑/网络 >> 程序设计 >> 其他编程语言
解析:
在3.8.2中需要导入junit.framework.中的类, 进行测试的类必须继承自TestCase类, 测试方法名称中需要含test字样, 可以仿大返在setup和teardown函数中管理一些每个测试函数都需要的资源比如数据库连接等,在测试函数中使用assert开头的函数来进行测试代码开发备饥.以下是从junit文档中摘出的范例:
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
/**
* Some simple tests.
*
*/
public class SimpleTest extends TestCase {
protected int fValue1;
protected int fValue2;
protected void setUp() {
fValue1= 2;
fValue2= 3;
}
public static Test suite() {
/*
* the type safe way
TestSuite suite= new TestSuite();
suite.addTest(
new SimpleTest("add") {
protected void runTest() { testAdd(); }
);
new SimpleTest("testDivideByZero") {
protected void runTest() { testDivideByZero(); }
return suite;
* the dynamic way
return new TestSuite(SimpleTest.class);
public void testAdd() {
double result= fValue1 ◆ fValue2;
// forced failure result == 5
assertTrue(result == 6);
public void testDivideByZero() {
int zero= 0;
int result= 8/zero;
result◆◆; // avoid warning for not using result
public void testEquals() {
assertEquals(12, 12);
assertEquals(12L, 12L);
assertEquals(new Long(12), new Long(12));
assertEquals("Size", 12, 13);
assertEquals("Capacity", 12.0, 11.99, 0.0);
public static void main (String[] args) {
junit.textui.TestRunner.run(suite());
在4.0.2中的变化是:
测试需要@.junit.Test的Annotation标记,其他部分也使用了Annotation标记,setup和teardown使用@.junit.Before 和仿野@.junit.After, 在eclipse3.1的环境中不支持4.0.2, 可以使用junit 4.0.2中提供的adapter类来帮助eclipse内置的junit发现新版本的测试函数
1、在Eclipse中对所要做测试的代码岁歼碰所在工程,添加JUnit4.0的JAR包。
2、在工程中,使用Eclipse的新建向导,对所要测试的代码文件,进行新建对应的JUnit类。
3、如果测试时需要有前提条件或者事后处理的话,要将相应的处理乎谈内容写在before和after方法中。
4、针对要测试的类,类中的public方法,写对应的测试方法。
5、测试代码写完编译没改辩有问题之后,执行测试类。可以在控制台上看到执行的测试结果。
JUnit是由 Erich Gamma 和 Kent Beck 编写的一个回归测试框架(regression testing framework)。Junit测试是戚信程序员测试,即所谓白盒高链轮测试,因为程序员知道被测试的唤歼软件如何(How)完成功能和完成什么样(What)的功能。Junit是一套框架,继承TestCase类,就可以用Junit进行自动测试了。
JUnit是一个开源的java单元测试框架。在1997年,由 Erich Gamma 和 Kent Beck 开发完成。这两个牛人中 Erich Gamma 是 GOF 之一;Kent Beck 则在 XP 中有重要的贡献(你觉得眼脊租熟一点都不奇怪)。
正如常言道:"麻雀虽小,五脏俱全。" JUnit设计的非常小巧,但是功能却非常强大。
下面是JUnit一些特性的总结:
1) 提供的API可以让你写出测试结果明确的可重用单元测试用例
2) 提供了三种方式来显示你的测试结果,而且还可以扩展
3) 提供了单元樱旦兆测试用迟芹例成批运行的功能
4) 超轻量级而且使用简单,没有商业性的欺骗和无用的向导
5) 整个框架设计良好,易扩展
对不同性质的被测对象,如Class,Jsp,Servlet,Ejb等,Junit有不同的使用技巧。由于本文的性质,以下仅以Class测试为例。
以上就是孜孜网小编大虾米为大家整理的junit单元测试_Junit单元测试自动注入失败相关主题介绍,如果您觉得小编更新的文章对您有所帮助,不要忘记讲本站分享给您身边的朋友哦!!
评论留言