Simple JUnit Testing

No code shall go to production without testing!

Objectives:

  • How to write simple test for simple java class?
  • How to run test using eclipse and maven?

Environment:

  • Eclipse
  • Maven

Libraries:

  • JUnit 4.11¬†junit-4.11.jar
  • hamcrest¬†hamcrest-core-1.3.jar
<dependency>
 <groupId>junit</groupId>
 <artifactId>junit</artifactId>
 <version>4.11</version>
 <scope>test</scope>
 </dependency>

( 1 ) Create Java Project

  • Use maven or eclipse

simple-junit-project

 

( 2 ) Java Code

Math.java

package com.hmkcode.junit;

public class Math 
{
    public static void main( String[] args )
    {
        System.out.println( "Hello World!" );
    }

    public double sum(double x, double y){
      return x+y;
    }
    public double multiply(double x, double y){
      return x*y;
    }
    public double divide(double x, double y){
      return x/y;
    }
    public double subtract(double x, double y){
      return x - y;  
}

MathTest.java

package com.hmkcode.junit;

import static org.junit.Assert.assertThat;

import org.junit.Rule;
import org.junit.Test;
import org.junit.Ignore;
import org.junit.rules.Timeout;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import static org.hamcrest.CoreMatchers.not;
import static org.hamcrest.CoreMatchers.is;

/**
 * Tests for {@link Math}.
 *
 * @author hmkcode@gmail.com (Hani HMK)
 */
@RunWith(JUnit4.class)
public class MathTest {

   @Rule
   public Timeout globalTimeout = new Timeout(3000); // 3 seconds max per method tested

  com.hmkcode.junit.Math math = new com.hmkcode.junit.Math();

  @Test
  @Ignore
   public void testAssertNotNull() {
      org.junit.Assert.assertNotNull("should not be null", math);
  }

    @Test
    public void testSum(){
      org.junit.Assert.assertTrue("failure - not equal", math.sum(3, 2) == 5);

      //to test timeout
      /*for (;;) {
        }*/
    }

    @Test
    public void testMultiply(){
       org.junit.Assert.assertTrue("failure - not equal", math.multiply(3, 2) == 6);
    }

    @Test
    public void testDivide(){
      double x = 3,y = 2;
      assertThat("failure - can't divide by 0",y, is(not(0.0)));
      org.junit.Assert.assertTrue("failure - not equal", math.divide(x, y) == 1.5);
    }

    @Test
    public void testSubtract(){
       org.junit.Assert.assertTrue("failure - not equal", math.subtract(3, 2) == 1);
    }

}

( 3 ) Run

  • From Eclipse

  • From Maven
simple-junit>mvn test

Source Code @ githum