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

JUnit - Time Test


May 15, 2021 jUnit


Table of contents


JUnit - Time Test

Junit provides a convenient option to pause. I f a test case takes more time than the specified number of milliseconds, Junit automatically marks it as a failure. eout parameter is @Test with a comment. N ow let's look at @test in the activity.

Create a class

  • Create a java class called MessageUtil JUNIT_WORKSPACE C:.java to test.
  • Add an infinite while loop within the printMessage() method.
/*
* 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 void printMessage(){
      System.out.println(message);
      while(true);
   }   

   // add "Hi!" to the message
   public String salutationMessage(){
      message = "Hi!" + message;
      System.out.println(message);
      return message;
   }   
} 

Create a Test Case class

  • Create a java test class .java TestJunit.
  • Add a pause time of 1000 to the testPrintMessage() test case.

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

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

public class TestJunit {

   String message = "Robert";   
   MessageUtil messageUtil = new MessageUtil(message);

   @Test(timeout=1000)
   public void testPrintMessage() { 
      System.out.println("Inside testPrintMessage()");     
      messageUtil.printMessage();     
   }

   @Test
   public void testSalutationMessage() {
      System.out.println("Inside testSalutationMessage()");
      message = "Hi!" + "Robert";
      assertEquals(message,messageUtil.salutationMessage());
   }
}

Create a Test Runner class

Create a java class JUNIT_WORKSPACE file named TestRunner in C:.java to perform the test sample.

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

The MessageUtil, Test case, and Test Runner classes are compiled with javac.

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

Now run Test Runner, which will run the test cases defined by the provided Test Case class.

C:\JUNIT_WORKSPACE>java TestRunner

Verify the output. The testPrintMessage() test case will mark the unit test failure.

Inside testPrintMessage()
Robert
Inside testSalutationMessage()
Hi!Robert
testPrintMessage(TestJunit): test timed out after 1000 milliseconds
false