05 - JUnit Tests

5.1 JUnit writing tests

5.2 JUnit executing tests

5.3 JUnit ignore test

5.4 JUnit time test

5.5 JUnit exceptions test

 

5.1 JUnit writing tests

We can try to write tests for example by using a POJO class, a Business logic class and a test class which can be run from Eclipse or with test runner.

Imagine an Internet shopping portal where we have to identify the calculation of shipping costs for a given order. Let’s consider we have an Order class that possesses the properties Cod and Total.

The Cod represents the cash on delivery (COD) property – the sale of goods by mail order where the payment is made on delivery rather than in advance (checks, credit or debit cards).

The total represents the total sum of the order.

public class Order {

      private double total;
     // Cash on delivery
      private boolean cod;
     /**
     * @return the total
     */
     public double getTotal() {
        return total;
     }
     /**
     * @param total the total to set
     */
     public void setTotal(double total) {
        this.total = total;
     }
     /**
     * @return the cod
     */
     public boolean isCod() {
        return cod;
     }
     /**
     * @param cod the cod to set
     */
     public void setCod(boolean cod) {
        this.cod = cod;
     }      
}

The Order class is used to

  • get/set the value of the total.
  • get/ set the value of the cod (true/false).

Create the business logic class  OrderBusinessLogic.java that will contain the business logic:

public class OrderBusinessLogic {
    // calculate the grand Shipping Cost 
     public double getShipping(Order order) {
         double shipping;
         if (order.getTotal() > 200)
         {
           shipping = 0;
         }
         else if (100 < order.getTotal() && order.getTotal() <= 200)
         {
           shipping = order.isCod()?9:5;
         }
         else
         {
           shipping = order.isCod()?10:15;
         }
         return shipping;
      }
}

OrderBusinessLogic class is used for calculating

  • the shipping – if the total cost of all ordered items is more than 200USD than will be no charge for shipping. Between 100 and 200 the items will be charged with COD at.  In all other cases shipping is 10 plus an extra for COD orders.

Create the OrderTest.java for testing the method of OrderBusinessLogic.java class. It will test the

  • the shipping value
import org.junit.Test;
import static org.junit.Assert.assertEquals;

import main.java.examples.Order;
import main.java.examples.OrderBusinessLogic;

public class OrderTest {

     Order order = new Order();
     OrderBusinessLogic orderBusinessLogic = new OrderBusinessLogic();

     //test to check shipping
       @Test
       public void testCalculateShipping() {
          order.setCod(true);
          order.setTotal(150);
          double shipping= orderBusinessLogic.getShipping(order);
          assertEquals(9.0, shipping, 0.0);
       }
}

OrderTest class tests:

  • the shipping value for an order.

If the test is run in Eclipse the result is:

The test can be executed also with TestRunner class :

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(OrderTest.class);
      for (Failure failure : result.getFailures()) {
         System.out.println(failure.toString());
      }
      System.out.println(result.wasSuccessful());
   }
}

In Eclipse the result is:

The tests can be run also from command line. If the folder c:\junit is the workspace folder we can compile the classes using references to junit library by simply adding –classpath option in the command:   

C:\junit>javac -classpath "C:\junit\junit-4.11.jar";"C:\junit\junit-master/lib/hamcrest-core-1.3.jar"; Order.java OrderBusinessLogic.java OrderTest.java TestRunner.java

C:\junit>java -classpath "C:\junit\junit-4.11.jar";"C:\junit\junit-master\lib\hamcrest-core-1.3.jar"; TestRunner

The output is:

5.2 JUnit executing tests

Sometimes it is preferred to run only some test cases even a new element is introduced. This can be done with org.junit.runner.JUnitCore class.

JUnitCore class is inbuilt in JUnit package. It is based on Façade design patterns. The class is used to run only specified test classes.

Let’s consider two test cases in our application MyFirstTest and MySecondTest we can run both tests with JUnitCore class after adding them in a list:

package test.java;

import static org.junit.Assert.*;

import org.junit.Test;

public class MyFirstTest {

    @Test
    public void testFirst()
    {
        assertTrue(true);
    }
}

package test.java;

import static org.junit.Assert.assertTrue;

import org.junit.Test;
public class MySecondTest {
    @Test
    public void testSecond()
    {
        assertTrue(true);
    }
}

package test.java;
import java.util.ArrayList;
import java.util.List;

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

@SuppressWarnings("rawtypes")
public class MyTestWithJUnitCore {

     public static void main(String[] args)
     {
        List<Class<?>> testCases = new ArrayList<Class<?>>();
        //Add test cases
        testCases.add(MyFirstTest.class);
        testCases.add(MySecondTest.class);
        for (Class testCase : testCases)
               {
                    runTestCase(testCase);
               }
     }

     private static void runTestCase(Class testCase)
    {
        Result result = JUnitCore.runClasses(testCase);
        for (Failure failure : result.getFailures())
        {
            System.out.println(failure.toString());
        }
        System.out.println(result.wasSuccessful());
    }
}

The output is:

The tests can also be run from the command line. If the folder c:\junit\junitcore is the workspace folder we can compile the classes using references to junit library by simply adding –classpath option in the command:

C:\junit\junitcore>javac -classpath "C:\junit\junit-4.11.jar";"C:\junit\junit-master/lib/hamcrest-core-1.3.jar"; MyFirstTest.java MySecondTest.java MyTestWithJUnitCore.java
C:\junit\junitcore>java -classpath "C:\junit\junit-4.11.jar";"C:\junit\junit-master\lib\hamcrest-core-1.3.jar"; MyTestWithJUnitCore

The output is:

5.3 JUnit ignore test

Some methods/code can be ignored during testing if they are not ready or if they are failing at running.

JUnit uses @Ignore annotation to avoid some methods to be executed.

  • if the annotation @Ignore appears before a method then that method will not be executed.
  • if the annotation @Ignore appears before a class, then none of its methods will be executed.
import org.junit.*;

public class MyIgnoreOneMethod {

     @Ignore("Will be ready soon")  
    @Test
    public void firstTestMethod() {  
      System.out.println("Method will be ready soon...");
    }  
}

The output in Eclipse is:

In the second case when all the methods are ignored:

import org.junit.Ignore;
import org.junit.Test;

@Ignore("Class will be ready soon...") 
public class MyIgnoreAllMethods {
     
   @Test
    public void firstTestMethod() {  
      System.out.println("First method will be ready soon...");
    }  
    @Test
    public void secondTestMethod() {  
      System.out.println("Second method will be ready soon...");
    }  
}

The output in Eclipse is:

5.4 JUnit time test

Methods can be tested if taking longer time to be executed than expected by specifying timeout

option of @Test annotation. The time is measured in milliseconds.

For example, if we add an infinite loop inside a method JUnit will mark the method as failed.

import org.junit.*;

public class MyTimeTest {

    @Test(timeout = 1000)  
    public void testTime() {  
        while (true);  
    }  
}

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

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

The result after run this test is:

The result in console is:

With command-line if the workspace folder is C:\junit\time_test then we can compile the classes using references to junit library by simply adding –classpath option in the command:

C:\junit\time_test>javac -classpath "C:\junit\junit-4.11.jar";"C:\junit\junit-master\lib\hamcrest-core-1.3.jar"; MyTimeTest.java MyTimeTestRunner.java


C:\junit\time_test>java -classpath "C:\junit\junit-4.11.jar";"C:\junit\junit-master\lib\hamcrest-core-1.3.jar"; MyTimeTestRunner

The result is:

5.5 JUnit exceptions test

In case of exceptions test, the test will pass only if an exception of the specified class is thrown by the test method. 

public class Person {
     private final String name;
      private final int age;
      
      /**
       * Creates a person with the specified name and age.
       *
       * @param name the name
       * @param age the age
       * @throws IllegalArgumentException if the age is not greater than zero
       */
       public Person(String name, int age) {
        this.name = name;
        this.age = age;
        if (age <= 0) {
          throw new IllegalArgumentException("Invalid age:" + age);
        }
      }
}

import org.junit.Test;

public class MyExceptionTest {

     @Test(expected = IllegalArgumentException.class)
    public void myTestExpectedException() {
      new Person("Tom", -1);
    }
}

The result in Eclipse after running the test in the class MyExceptionTest is:


If the test is called with TestRunner class:

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

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

The result in console is:

With command-line if the workspace folder is C:\junit\exception_test then we can compile the classes using references to junit library by simply adding –classpath option in the command:

C:\junit\exception_test>javac -classpath "C:\junit\junit-4.11.jar";"C:\junit\junit-master\lib\hamcrest-core-1.3.jar"; Person.java MyExceptionTest.java TestRunnerException.java


C:\junit\exception_test>java -classpath "C:\junit\junit-4.11.jar";"C:\junit\junit-master\lib\hamcrest-core-1.3.jar"; TestRunnerException

The result is:

The test case is passed. 

Like us on Facebook