Junit test for private methods reflection example

In this post, we will see how to write test cases for private methods using reflection.

 

We have two classes Employee.java and EmployeeTest.java in the same package reflectionjunit. We have a private method getEmployeename() which returns a string. We are going to write JUnit test cases for this method.

Employee.java

package reflectionjunit;


public class Employee {
	
private String getEmployeename(String name) {
		
		//some dummy logic
		if(name.equals("ram")) {
			return name;
		}
		
		return "mohan";
		
	}
}

EmployeeTest.java

package reflectionjunit;

import static org.junit.Assert.assertEquals;

import java.lang.reflect.Method;

import org.junit.BeforeClass;
import org.junit.Test;

public class EmployeeTest {
	
	public static Employee employeeObj;
	
	@BeforeClass
    public static void beforeClass() {
		employeeObj = new Employee();
    }
	@Test
	public void testGetEmployeenameSuccess() throws Exception {
		String name = "ram";

		Method method = Employee.class.getDeclaredMethod("getEmployeename", String.class);
		method.setAccessible(true);
		String returnValue = (String) method.invoke(employeeObj, name);

		assertEquals(returnValue, "ram");
	}
}

 

Run the above code as Junit.

Yes, we have a success result.

 

Let’s check the fail case.

package reflectionjunit;

import static org.junit.Assert.assertEquals;

import java.lang.reflect.Method;

import org.junit.BeforeClass;
import org.junit.Test;

public class EmployeeTest {
	
	public static Employee employeeObj;
	
	@BeforeClass
    public static void beforeClass() {
		employeeObj = new Employee();
    }
	@Test
	public void testGetEmployeenameFailure() throws Exception {
		String name = "ram";

		Method method = Employee.class.getDeclaredMethod("getEmployeename", String.class);
		method.setAccessible(true);
		String returnValue = (String) method.invoke(employeeObj, name);

		assertEquals(returnValue, "sohan");
	}
}

Output is –

 

This is the fail case. Since we are passing name is sohan but it’s expecting ram.