特点:
-
JUnit 是一个开放的资源框架,用于编写和运行测试。
-
提供注释来识别测试方法。
-
提供断言来测试预期结果。
-
提供测试运行来运行测试。
-
JUnit 测试允许你编写代码更快,并能提高质量。
-
JUnit 优雅简洁。没那么复杂,花费时间较少。
-
JUnit 测试可以自动运行并且检查自身结果并提供即时反馈。所以也没有必要人工梳理测试结果的报告。
-
JUnit 测试可以被组织为测试套件,包含测试用例,甚至其他的测试套件。
-
JUnit 在一个条中显示进度。如果运行良好则是绿色;如果运行失败,则变成红色。
-
JUnit测试减少后期维护时间以及成本
导入JUnit4单元测试所需的jar包
打开开发工具 eclipse|myeclipse -> 对应项目右击 > Build Path > Add Library > JUnit
> 选择版本JUnit4 > Finish
单元模块测试——单个类
1、使用@Test注解
例子:
import static org.junit.Assert.assertEquals;
import org.junit.Test;
public class Test01
{
final static String CH = "中国";
@Test
//(命名格式建议用test+方法名)
public void testCode()
throws Exception
{
assertEquals("中国", CH);
}}
2、extend TestCase类
例子:
import junit.framework.TestCase;
public class Test01 extends TestCase
{
final static String CH = "中国";
//(命名格式建议用test+方法名) //继承TestCase,如命名方法没有test作为前缀则报错
public void testCode()
throws Exception
{
assertEquals("中国", CH);
}}
单元模块测试——多个类
3、使用JUnitCore.runClasses(StudentTest01.class)返回Result类型;
调用for (Failure failure : result.getFailures())进行遍历
例子:
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;
public class TestRunner
{public static void main(String[] args)
{
// TODO Auto-generated method stub
Result result = JUnitCore.runClasses(StudentTest01.class);
for (Failure failure : result.getFailures())
{
System.out.println(failure.toString());
}
// 测试过程中是否成功
System.out.println(result.wasSuccessful());
}
}4、使用注解 @RunWith、@Suite.SuiteClasses
例子:
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
@RunWith(Suite.class)
@Suite.SuiteClasses({
//测试类作为参数,多个参数用逗号隔开
StudentTest01.class, StudentTest02.class})
public class AllTest
{ }5、使用TestSuite类中的addTestSuite添加测试类、run(new TestResult())运行测试类
例子:
import junit.framework.TestResult;
import junit.framework.TestSuite;
public class AllTest
{
public static void main(String[] args)
{
TestSuite testSuite = new TestSuite();
testSuite.addTestSuite(StudentTest01.class);
testSuite.addTestSuite(StudentTest02.class);
testSuite.run(new TestResult());
}}