JUnit常用API

JUnit 中最重要的包是 junit.framework,它包含了所有的核心类。一些重要的类如下:

Sr.No.Class NameFunctionality
1AssertA set of assert methods.
2TestCaseA test case defines the fixture to run multiple tests.
3TestResultA TestResult collects the results of executing a test case.
4TestSuiteA TestSuite is a composite of tests.

Assert Class

以下是 org.junit.Assert 类的声明

public class Assert extends java.lang.Object

此类提供了一组对编写测试有用的断言方法。仅记录失败的断言。 Assert类的一些重要方法如下:

Sr.No.Methods & Description
1

void assertEquals(boolean expected, boolean actual)

Checks that two primitives/objects are equal.

2

void assertFalse(boolean condition)

Checks that a condition is false.

3

void assertNotNull(Object object)

Checks that an object isn't null.

4

void assertNull(Object object)

Checks that an object is null.

5

void assertTrue(boolean condition)

Checks that a condition is true.

6

void fail()

Fails a test with no message.

让我们在一个例子中使用上面提到的一些方法。创建一个名为 TestJunit1.java 的 java 类文件

import org.junit.Test;
import static org.junit.Assert.*;

public class TestJunit1 {
   @Test
   public void testAdd() {
      //test data
      int num = 5;
      String temp = null;
      String str = "Junit is working fine";

      //check for equality
      assertEquals("Junit is working fine", str);
      
      //check for false condition
      assertFalse(num > 6);

      //check for not null value
      assertNotNull(temp);
   }
}

接下来,创建一个名为 TestRunner1.java 的 java 类文件

import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;

public class TestRunner1 {
   public static void main(String[] args) {
      Result result = JUnitCore.runClasses(TestJunit1.class);
		
      for (Failure failure : result.getFailures()) {
         System.out.println(failure.toString());
      }
		
      System.out.println(result.wasSuccessful());
   }
}  

验证输出: true

TestCase Class

以下是 org.junit.TestCase 类的声明

public abstract class TestCase extends Assert implements Test

测试用例定义了运行多个测试的夹具。 TestCase类的一些重要方法如下

Sr.No.Methods & Description
1

int countTestCases()

Counts the number of test cases executed by run(TestResult result).

2

TestResult createResult()

Creates a default TestResult object.

3

String getName()

Gets the name of a TestCase.

4

TestResult run()

A convenience method to run this test, collecting the results with a default TestResult object.

5

void run(TestResult result)

Runs the test case and collects the results in TestResult.

6

void setName(String name)

Sets the name of a TestCase.

7

void setUp()

Sets up the fixture, for example, open a network connection.

8

void tearDown()

Tears down the fixture, for example, close a network connection.

9

String toString()

Returns a string representation of the test case.

让我们在一个例子中使用上面提到的一些方法。创建一个名为 TestJunit2.java 的 java 类文件

import junit.framework.TestCase;
import org.junit.Before;
import org.junit.Test;

public class TestJunit2 extends TestCase  {
   protected double fValue1;
   protected double fValue2;
   
   @Before 
   public void setUp() {
      fValue1 = 2.0;
      fValue2 = 3.0;
   }
	
   @Test
   public void testAdd() {
      //count the number of test cases
      System.out.println("No of Test Case = "+ this.countTestCases());
		
      //test getName 
      String name = this.getName();
      System.out.println("Test Case Name = "+ name);

      //test setName
      this.setName("testNewAdd");
      String newName = this.getName();
      System.out.println("Updated Test Case Name = "+ newName);
   }
	
   //tearDown used to close the connection or clean up activities
   public void tearDown(  ) {
   }
}

接下来,创建一个名为 TestRunner2.java 的 java 类文件

import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;

public class TestRunner2 {
   public static void main(String[] args) {
      Result result = JUnitCore.runClasses(TestJunit2.class);
		
      for (Failure failure : result.getFailures()) {
         System.out.println(failure.toString());
      }
		
      System.out.println(result.wasSuccessful());
   }
} 

验证输出

No of Test Case = 1
Test Case Name = testAdd
Updated Test Case Name = testNewAdd
true

TestResult Class

以下是 org.junit.TestResult 类的声明

public class TestResult extends Object

TestResult 收集执行测试用例的结果。它是收集参数模式的一个实例。测试框架区分失败和错误。预期会发生故障并使用断言进行检查。错误是预料之外的问题,例如 ArrayIndexOutOfBoundsException。TestResult类的一些重要方法如下:

Sr.No.Methods & Description
1

void addError(Test test, Throwable t)

Adds an error to the list of errors.

2

void addFailure(Test test, AssertionFailedError t)

Adds a failure to the list of failures.

3

void endTest(Test test)

Informs the result that a test was completed.

4

int errorCount()

Gets the number of detected errors.

5

Enumeration<TestFailure> errors()

Returns an Enumeration for the errors.

6

int failureCount()

Gets the number of detected failures.

7

void run(TestCase test)

Runs a TestCase.

8

int runCount()

Gets the number of run tests.

9

void startTest(Test test)

Informs the result that a test will be started.

10

void stop()

Marks that the test run should stop.

创建一个名为 TestJunit3.java 的 java 类文件

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
   }
}

接下来,创建一个名为 TestRunner3.java 的 java 类文件

import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;

public class TestRunner3 {
   public static void main(String[] args) {
      Result result = JUnitCore.runClasses(TestJunit3.class);

      for (Failure failure : result.getFailures()) {
         System.out.println(failure.toString());
      }
		
      System.out.println(result.wasSuccessful());
   }
}  

TestSuite Class

以下是 org.junit.TestSuite 类的声明:

public class TestSuite extends Object implements Test

TestSuite 是测试的组合。它运行一组测试用例。 TestSuite类的一些重要方法如下

Sr.No.Methods & Description
1

void addTest(Test test)

Adds a test to the suite.

2

void addTestSuite(Class<? extends TestCase> testClass)

Adds the tests from the given class to the suite.

3

int countTestCases()

Counts the number of test cases that will be run by this test.

4

String getName()

Returns the name of the suite.

5

void run(TestResult result)

Runs the tests and collects their result in a TestResult.

6

void setName(String name)

Sets the name of the suite.

7

Test testAt(int index)

Returns the test at the given index.

8

int testCount()

Returns the number of tests in this suite.

9

static Test warning(String message)

Returns a test which will fail and log a warning message.

创建一个名为 JunitTestSuite.java 的 java 类文件

import junit.framework.*;

public class JunitTestSuite {
   public static void main(String[] a) {
      // add the test's in the suite
      TestSuite suite = new TestSuite(TestJunit1.class, TestJunit2.class, TestJunit3.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

总结

简单介绍了JUnit框架中四个最重要的API,同时需要理解的是,这些API体现了JUnit中最重要的四个基本概念:测试用例,测试集,测试断言和测试结果。以后的所有的一些高级概念都是这些基本概念的组合和深化。

 

 

 

 

版权声明:著作权归作者所有。

thumb_up 0 | star_outline 0 | textsms 0