Testing Output using assertEquals
Scenario1.java

public class Scenario
{	
  public int Square(int no)
  {
    return no*no;
  }
}

SquareTest.java

public class SquareTest 
{
  @Test
  public void test() 
  {
    int SquareNo = new Test1().Square(5);		
    assertEquals(25, SquareNo);
  }
}

Scenario2.java(word Counter)

public class Scenario2 
{	
 public int repeatedWords(String pWord)
 {
   int count = 0;
	
   for (int j = 0; j < pWord.length(); j++) 
   {
     if(pWord.charAt(j) == 'a')
     {
       count++;	
     }
   }	
    return count;
 }
}

RepeatTest.java

public class RepeatTest {
   @Test
   public void test() {
     Scenario2 objScenario2 = new Scenario2();		
     assertEquals(objScenario2.repeatedWords("alphabet"), 2);		
   }
}

Test suite is used to bundle a few unit test cases and run them together. In JUnit, both @RunWith and @SuiteClasses annotations are used to run the suite tests.

AllTests.java (TestSuite)

@RunWith(Suite.class)
@SuiteClasses({ RepeatTest.class, SquareTest.class })
public class AllTests {

}

Now Lets take a Real Life Scenario of Bank Account
Account.java

public class Account 
{
	public int Balance;
	
	public Account()
	{
		Balance = 0;
	}
	
	public int getAccBalance()
	{
		return Balance;
	}
	
	public void getCash(int pCash)
	{
		Balance = Balance - pCash;
	}
	
	public void putCash(int pCash)
	{
		Balance = Balance + pCash;
	}
}

BankTest.java

public class BankTest 
{
	Account objAcc = new Account();
	
	@Test
	public void checkAccBalanceTest()
	{
		assertEquals(objAcc.getAccBalance(), 0);
	}
	
	@Test
	public void checkBalAfterDepositTest()
	{
		objAcc.putCash(50);
		assertEquals(objAcc.getAccBalance(), 50);
	}
	
	@Test
	public void checkBalAfterWithdrawTest()
	{
		objAcc.getCash(30);		
		assertEquals(objAcc.getAccBalance(), 20);
	}
}

Points to Note

  1. The methods in BankTest ends with Test Suffix.This ensures the test cases are executed in order.
  2. The Account.java and BankTest.java are two different projects.In BankTest project the other project is added in Java Build Path

DBUtilsTest.java

public class DBUtilsTest
{	
	public void getDBRecordsSQLTest()
	{	
		DBUtils objDBUtils 	 = new DBUtils();
		ResultSet resultSet  = objDBUtils.getDBRecordsSQL("SELECT 78985450.1245487986418648 decimal_val FROM dual");
		
		double expectedValue   = 1245.654618764;
		double dbValue 	 	   = 0; 
		double toleranceLimit  = 0.000000001;
		
		try
		{
			 while(resultSet.next())
			 {
				dbValue =  resultSet.getDouble("decimal_val");
				assertEquals(expectedValue, dbValue, toleranceLimit);
			 }
		} catch (SQLException e)
		{
			e.printStackTrace();
		}
		
		objDBUtils.closeConnection();
	}
	
	@Test
	public void getDBRecordsProcTest()
	{	
		DBUtils objDBUtils 	 = new DBUtils();
		ResultSet resultSet  = objDBUtils.getDBRecordsProc("{call TESTJUNIT.junitproc(?)}");
		
		double expectedValue   = 7.89854501245488E7;
		double dbValue 	 	   = 0; 
		double toleranceLimit  = 0.000000001;
		
		try
		{
			 while(resultSet.next())
			 {
				dbValue =  (double) resultSet.getDouble(1);				
				assertEquals(expectedValue, dbValue, toleranceLimit);
			 }
		} catch (SQLException e)
		{
			e.printStackTrace();
		}
		
		objDBUtils.closeConnection();
	}
}

DBUtils.java

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import oracle.jdbc.OracleTypes;

public class DBUtils
{
	Connection  conn  = null;
    Statement 	stmt  = null;
    ResultSet   rs    = null;
	
	public ResultSet getDBRecordsSQL(String pQuery)
	{    
	    try
	    {
	    	conn = DriverManager.getConnection("hostname", "admin", "admin123");
	        stmt = (Statement)conn.createStatement();
	        rs 	 = stmt.executeQuery(pQuery);
	     	
	    } catch (SQLException e)
		{
			e.printStackTrace();
		}
	    
		return rs;
	}
	
	public ResultSet getDBRecordsProc(String pQuery)
	{	
		CallableStatement stmt  = null; 
		
		try
	    {
	    	conn = DriverManager.getConnection("hostname", "admin", "admin123");	        
	        stmt = conn.prepareCall(pQuery);	        
	        stmt.registerOutParameter(1, OracleTypes.CURSOR);
	        stmt.execute();
	        rs = (ResultSet) stmt.getObject(1);
	    } catch (SQLException e)
		{
			e.printStackTrace();
		}
		
		return rs;
	}
	
	public void closeConnection()
	{
		if (rs  != null) try { rs.close();  } catch (SQLException ignore) {}
        if (stmt  != null) try { stmt.close();  } catch (SQLException ignore) {}
        if (conn != null) try { conn.close(); } catch (SQLException ignore) {}
	}
}

Basic Test case which Fails

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

public class Junit1 {	
 @Test
 public void basicTestFail()
 {
  fail("The Test Failed");
 }
}

There is No pass method in JUnit like fail method.

As long as the test doesn’t throw an exception, it passes, unless your @Test annotation specifies an expected exception. I suppose a pass() could throw a special exception that JUnit always interprets as passing, so as to short circuit the test, but that would go against the usual design of tests (i.e. assume success and only fail if an assertion fails) and, if people got the idea that it was preferable to use pass(), it would significantly slow down a large suite of passing tests (due to the overhead of exception creation). Failing tests should not be the norm, so it’s not a big deal if they have that overhead.

Tests to verify the correctness of a program’s behavior.Verifying the correctness of a program’s behaviour by inspecting the content of output statements.Its looking manually for abnormal output.

Example1

StringHelper.java

package com.mugil.junit.tutor;

public class StringHelper
{	
	public static void main(String[] args)
	{
		StringHelper objStringHelper = new StringHelper();
		System.out.println(objStringHelper.wordATrimmer("PABBB"));
	}
	
	public String wordATrimmer(String pWord)
	{
  	   String pTempString = pWord.substring(0, 2);			   
           if(pTempString.contains("A")) return pWord.replace("A", "");		
 	   pTempString = pWord.substring(2);		
	   return pWord;
	}
}

StringHelperTest.java

package com.mugil.junit.tutor;

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

public class StringHelperTest 
{
	@Test
	public void test() 
        {
		StringHelper objStringHelper = new StringHelper();
		String expectedOP            = "MMG";
		String actOP                 = objStringHelper.wordATrimmer("AAMMG");
		
		assertEquals(expectedOP, actOP);
	}
}

@Test comes from org.junit.Test Package
assertEquals – helps in performing String, Boolean and Other Comparison.

As you have seen above StringHelper.java is the actual file which has the function.StringHelperTest.java is the file in which test of the functionality is to be carried out.This java file is created in a new source folder test.By using assert equals method we are comparing whether the expected Op and actual OP are same.

@Test annotation at the top of test method tells the JVM to run this method

assertTrue(boolean)
assertTrue(boolean true) will return true
assertFalse(boolean false) will return true

To make sure the code is behaving the right way we can use asserttrue() and assertfalse() methods.
StringHelper.java

package com.mugil.junit.tutor;

public class StringHelper
{	
	public boolean areFirstTwoandLastTwoStringsSame(String Name)
	{
		if(Name.length() <  2) return false;		
		if(Name.length() == 2) return true;
		
		String firstChars = Name.substring(0, 2);
		String lastChars  = Name.substring(Name.length()-2);
		
		if(firstChars == lastChars)
		  return true;
		else
		  return false;
	}
}

StringHelperTest.java

 package com.mugil.junit.tutor;

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

public class StringHelperTest 
{
  @Test
  public void test() 
  {
    StringHelper objStringHelper = new StringHelper();
    assertTrue(objStringHelper.areFirstTwoandLastTwoStringsSame("AB"));
    assertFalse(objStringHelper.areFirstTwoandLastTwoStringsSame("ABAB"));
  }
}

The above code checks whether First and Last two characters are same and returns true or false based on input to method areFirstTwoandLastTwoStringsSame.

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

public class StringHelperTest 
{
	
  @Before
  public void before()
  {	
    System.out.println("Before Test");
  }
	
  @After
  public void after()
  {	
    System.out.println("After Test");
  }

  @Test
  public void test1() 
  {
    System.out.println("Test1");
  }
	
  @Test
  public void test2() 
  {
    System.out.println("Test2");
  }	
}

The before and after methods are used to run a case before and after actual test started.

The output of the above code would be

Before Test
Test1
After Test
Before Test
Test2
After Test

You can also run a test before and after the class run as below

import org.junit.AfterClass;
import org.junit.BeforeClass;

@BeforeClass
public static void beforeClass()
{	
  System.out.println("Before Test");
}
	
@AfterClass
public static void afterClass()
{	
  System.out.println("After Test");
}

@Test
public void test1() 
{
  StringHelper objStringHelper = new StringHelper(); 
  System.out.println("During Test");
}

Output
Before Test
During Test
After Test

BeforeClass and AfterClass is run only once when object for class is created.Note the static before beforeClass and afterClass methods.

Typical Example for Using before and after methods where object for class created in before method and object assigned null in after method.

public class StringHelperTest 
{	
  StringHelper objStringHelper1;
	
  @Before
  public void before()
  {	
     objStringHelper1 = new StringHelper(); 
  }
	
  @After
  public void afterClass()
  {	
    objStringHelper1 = null;
  }

  @Test
  public void test1() 
  {   
    System.out.println("Test Cases");
  }	
}

How to check expected array is returned in Output

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

public class StringHelperTest 
{
  @Test
  public void test1() 
  {
    int[] arrNums1 = {5,4,3,2,1};
    Arrays.sort(arrNums1);		
    int[] arrNums2 = {1,2,3,4,5};
		
    assertArrayEquals(arrNums1, arrNums2);
  }
}

assertArrayEquals method comes from org.junit.Assert Package

We are going to look for expected exception is getting thrown or not

Testing for Exception

import java.util.Arrays;
import org.junit.Test;

public class StringHelperTest 
{
  @Test(expected=NullPointerException.class)
  public void test1() 
  {
    int[] arrNums1 = null;
    Arrays.sort(arrNums1);
  }
}

Testing for Performance – How Much time is taken by code block to execute the code.

In the below code we are going to estimate actual time taken by the code block to execute

 public class StringHelperTest 
 {
   @Test(timeout=100)
   public void test1() 
   {
     for (int i = 0; i < 1000000; i++) 
     {
	    int[] arrNumbs = {i-1, i, i+1};
          Arrays.sort(arrNumbs);
     }
   }
}

timeout=100 – is going to tell the code should complete the execution within 100 milliseconds.If it fails I should optimize the code by performance tweaks to boost codes performance.