Pages

Showing posts with label JUnit. Show all posts
Showing posts with label JUnit. Show all posts

Wednesday, March 13, 2013

A Simple JUnit example

JUnit is unit testing tool/framework for the Java programming language.

The methods that we want to test must be annotated with @Test annotation.

Look at the below sample code for quick reference.

Jar : Include junit-4.x.jar in your build path.

package com.j4b.junit;

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

class HelloWorld {
 int x = 0;
 
 public String sayHello(){
  if(x == 0)
   throw new NullPointerException();
  return "Hello World";
 }

}

public class TestHelloWorld {
 
 @Test (expected= NullPointerException.class)
 public void testSayHello(){
  HelloWorld h = new HelloWorld();
  assertEquals("Hello World",h.sayHello());
 }
}
Now run the above code as JUnit Test and check.

Observe in the above code that - testSayHello() is a public method and returns void.

assertEquals() takes two params, 1st one is the Expected output and 2nd is the actual method we are calling.

@Test (expected= NullPointerException.class) - is a test method and it may throw a NullPointerException. So if even though it throws NullPointerException, JUnit Test will pass.