Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

JUnit - Perform the test


May 15, 2021 jUnit


Table of contents


JUnit - Perform the test

Test cases are executed using the JUnitCore class. J UnitCore is the skin class that runs the test. I t supports running JUnit 4 tests, JUnit 3.8.x tests, or their mixing. T o run a test from the command line, run java org.junit.runner.JUnitCore. For a test run that has only one run, you can use the static method runClasses.

Here's a statement from the org.junit.runner.JUnitCore class:

public class JUnitCore extends java.lang.Object

Create a class

  • In Directory C: Create a JUNIT_WORKSPACE Java class named MessageUtil in the .java.
/*
* This class prints the given message on console.
*/
public class MessageUtil {

   private String message;

   //Constructor
   //@param message to be printed
   public MessageUtil(String message){
      this.message = message;
   }

   // prints the message
   public String printMessage(){
      System.out.println(message);
      return message;
   }   
}  

Create a test case class

  • Create a java test class called TestJunit .java.
  • Add a test method to the class testPrintMessage().
  • Add a comment to the method testPrintMessage() @Test.
  • Implement the test conditions and check the test conditions with Junit's assertEquals API.

In Directory C: You can JUNIT_WORKSPACE a java class file named TestJunit .java

import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class TestJunit {

   String message = "Hello World";  
   MessageUtil messageUtil = new MessageUtil(message);

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

Create a TestRunner class

Next, let's go to Directory C: JUNIT_WORKSPACE create a java class file named TestRunner.java to execute test cases, export the JUnitCore class, and use the runClasses() method to use the test class name as an argument.

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());
   }
}  

Use the javac command to compile the Test case and Test Runner classes.

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

Now run Test Runner and it will automatically run the test samples defined in the Test Case class.

C:\JUNIT_WORKSPACE>java TestRunner

Verify the output

Hello World
true