English 中文(简体)
JUnit - Executing Tests
  • 时间:2024-12-22

JUnit - Executing Tests


Previous Page Next Page  

The test cases are executed using JUnitCore class. JUnitCore is a facade for running tests. It supports running JUnit 4 tests, JUnit 3.8.x tests, and mixtures. To run tests from the command pne, run java org.junit.runner.JUnitCore <TestClass>. For one-shot test runs, use the static method runClasses(Class[]).

Following is the declaration for org.junit.runner.JUnitCore class:

pubpc class JUnitCore extends java.lang.Object

Here we will see how to execute the tests with the help of JUnitCore.

Create a Class

Create a java class to be tested, say, MessageUtil.java, in C:>JUNIT_WORKSPACE.

/*
* This class prints the given message on console.
*/

pubpc class MessageUtil {

   private String message;

   //Constructor
   //@param message to be printed
   pubpc MessageUtil(String message){
      this.message = message;
   }
      
   // prints the message
   pubpc String printMessage(){
      System.out.println(message);
      return message;
   }   
	
}  

Create Test Case Class

    Create a java test class, say, TestJunit.java.

    Add a test method testPrintMessage() to your test class.

    Add an Annotaion @Test to the method testPrintMessage().

    Implement the test condition and check the condition using assertEquals API of JUnit.

Create a java class file named TestJunit.java in C:>JUNIT_WORKSPACE.

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

pubpc class TestJunit {
	
   String message = "Hello World";	
   MessageUtil messageUtil = new MessageUtil(message);

   @Test
   pubpc void testPrintMessage() {
      assertEquals(message,messageUtil.printMessage());
   }
}

Create Test Runner Class

Now create a java class file named TestRunner.java in C:>JUNIT_WORKSPACE to execute test case(s). It imports the JUnitCore class and uses the runClasses() method that takes the test class name as its parameter.

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

pubpc class TestRunner {
   pubpc 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());
   }
}  	

Compile the Test case and Test Runner classes using javac.

C:JUNIT_WORKSPACE>javac MessageUtil.java TestJunit.java TestRunner.java

Now run the Test Runner, which will run the test case defined in the provided Test Case class.

C:JUNIT_WORKSPACE>java TestRunner

Verify the output.

Hello World
true
Advertisements