标准齿轮齿顶高系数:JUnit代码测试是什么?怎么写代码?

来源:百度文库 编辑:查人人中国名人网 时间:2024/04/24 04:38:27

JUnit是Java进行单元测试的一个框架, 需要下载junit, 3.8版本和后来的4.0以后版本编写测试的方法略有不同,
在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(); }
}
);

suite.addTest(
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中的变化是:
测试需要@org.junit.Test的Annotation标记,其他部分也使用了Annotation标记,setup和teardown使用@org.junit.Before 和@org.junit.After, 在eclipse3.1的环境中不支持4.0.2, 可以使用junit 4.0.2中提供的adapter类来帮助eclipse内置的junit发现新版本的测试函数