扫码一下
查看教程更方便
junit 是一个回归测试框架,被开发者用于实施对应用程序的单元测试,加快程序编制速度,同时提高编码的质量。junit 测试框架能够轻松完成以下任意两种结合:
junit 测试框架具有以下重要特性:
测试工具是一整套固定的工具用于基线测试。测试工具的目的是为了确保测试能够在共享且固定的环境中运行,因此保证测试结果的可重复性。它包括:
setup()
方法。teardown()
方法。让我们来看一个例子:
import junit.framework.*;
public class javatest extends testcase {
protected int value1, value2;
// assigning the values
protected void setup(){
value1=3;
value2=3;
}
// test method to add two values
public void testadd(){
double result= value1 value2;
asserttrue(result == 6);
}
}
测试套件意味捆绑几个测试案例并且同时运行。在 junit 中,@runwith
和 @suite
都被用作运行测试套件。以下为使用 testjunit1 和 testjunit2 的测试分类:
import org.junit.runner.runwith;
import org.junit.runners.suite;
//junit suite test
@runwith(suite.class)
@suite.suiteclasses({
testjunit1.class ,testjunit2.class
})
public class junittestsuite {
}
import org.junit.test;
import org.junit.ignore;
import static org.junit.assert.assertequals;
public class testjunit1 {
string message = "robert";
messageutil messageutil = new messageutil(message);
@test
public void testprintmessage() {
system.out.println("inside testprintmessage()");
assertequals(message, messageutil.printmessage());
}
}
import org.junit.test;
import org.junit.ignore;
import static org.junit.assert.assertequals;
public class testjunit2 {
string message = "robert";
messageutil messageutil = new messageutil(message);
@test
public void testsalutationmessage() {
system.out.println("inside testsalutationmessage()");
message = "hi!" "robert";
assertequals(message,messageutil.salutationmessage());
}
}
测试运行器 用于执行测试案例。以下为假定测试分类成立的情况下的例子:
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) {
result result = junitcore.runclasses(testjunit.class);
for (failure failure : result.getfailures()) {
system.out.println(failure.tostring());
}
system.out.println(result.wassuccessful());
}
}
测试分类是在编写和测试 junit 的重要分类。几种重要的分类如下: