一、Junit概述
JUnit 是一个 Java 编程语言的单元测试框架。JUnit 在测试驱动的开发方面有很重要的发展,是起源于 JUnit 的一个统称为 xUnit 的单元测试框架之一。
JUnit 促进了“先测试后编码”的理念,强调建立测试数据的一段代码,可以先测试,然后再应用
特点:
JUnit 是一个开放的资源框架,用于编写和运行测试。
提供注释来识别测试方法。
提供断言来测试预期结果。
提供测试运行来运行测试。
JUnit 测试允许你编写代码更快,并能提高质量。
JUnit 优雅简洁。没那么复杂,花费时间较少。
JUnit 测试可以自动运行并且检查自身结果并提供即时反馈。所以也没有必要人工梳理测试结果的报告。
JUnit 测试可以被组织为测试套件,包含测试用例,甚至其他的测试套件。
JUnit 在一个条中显示进度。如果运行良好则是绿色;如果运行失败,则变成红色。
二、常用方法
package junit;
import static org.junit.Assert.*;
import org.junit.Test;
public class TestJunit1 {
@Test
public void testAdd() {
int num= 5;
String temp= null;
String str= "Junit is working fine";
assertEquals("Junit is working fine", str);
assertFalse(num > 6);
assertNotNull(str);
}
}
package junit;
import junit.framework.TestCase;
import org.junit.Before;
import org.junit.Test;
public class JunitTest2 extends TestCase {
protected double fValue1;
protected double fValue2;
@Before
public void setUp() {
fValue1= 2.0;
fValue2= 3.0;
}
@Test
public void testAdd() {
//测试用例的数量
System.out.println("No of Test Case = "+ this.countTestCases());
//用例名称
String name= this.getName();
System.out.println("Test Case Name = "+ name);
//设置新的测试用例名称
this.setName("testNewAdd");
String newName= this.getName();
System.out.println("Updated Test Case Name = "+ newName);
}
//tearDown方法被使用于网络关闭后等情况
public void tearDown(){
}
}
import org.junit.Test;
import junit.framework.AssertionFailedError;
import junit.framework.TestResult;
public class TestJunit3 extends TestResult {
// add the error
public synchronized void addError(Test test, Throwable t) {
super.addError((junit.framework.Test) test, t);
}
// add the failure
public synchronized void addFailure(Test test, AssertionFailedError t) {
super.addFailure((junit.framework.Test) test, t);
}
@Test
public void testAdd() {
// add any test
}
// Marks that the test run should stop.
public synchronized void stop() {
//stop the test here
}
}
package junit;
import junit.framework.TestResult;
import junit.framework.TestSuite;
/**
* TestSuite 类是测试的组成部分。它运行了很多的测试案例。
*/
public class JunitTestSuite {
public static void main(String[] args) {
TestSuite suite=new TestSuite(TestJunit1.class,JunitTest2.class,TestJunit.class);
TestResult result = new TestResult();
suite.run(result);
System.out.println("Number of test cases:"+result.runCount());
}
}
输出如下:
No of Test Case = 1
Test Case Name = testAdd
Updated Test Case Name = testNewAdd
Number of test cases:3