How to test private method using PowerMock

PowerMock provides org.powermock.reflect.Whitebox class to test private methods, here one example to test private methods using PowerMock.

Main Class

package com.pretech;
public class EmployeeDetails {
	
	private int calculateSalary(int basic, int hra, int da) {
		return basic + hra + da;
	}
}

Test Class

package com.pretech;
import org.junit.Assert;
import org.junit.Test;
import org.powermock.reflect.Whitebox;
public class EmployeeDetailsTest {
	@Test
	public void testCalculateSalary() throws Exception {
		EmployeeDetails empDetails = new EmployeeDetails();
		int sum = Whitebox.<Integer> invokeMethod(empDetails,
				"calculateSalary", 1000, 500, 250);
		Assert.assertEquals(1750, sum);
	}
}

Output



image


No comments:

Post a Comment

Model Context Protocol (MCP) — Complete Guide for Backend Engineers

  Model Context Protocol (MCP) — Complete Guide for Backend Engineers Build Tools, Resources, and AI-Driven Services Using LangChain Moder...

Featured Posts