Test private methods in JUnit

procedure

  1. Create an instance of the implementation class
  2. Create an instance of the private method
  3. Allow access to private methods
  4. Pass the implementation class instance and method arguments to the instantiated method

Sample code

TargetClass.java


private String privateMethod(String message) {
	return "Input: " + message;
}

TargetClassTest.java


@Test
public void privateMethodTest() {

	// 1.Create an instance of the implementation class
	TargetClass targetClass = new TargetClass();

	// 2.Create an instance of a private method
	Method privateMethod = TargetClass.class.getDeclaredMethod("privateMethod", String.class);

	// 3.Allow access to private methods
	privateMethod.setAccessible(true);

	// 4.Pass the implementation class instance and method arguments to the instantiated method
	String actual = (String) privateMethod.invoke(targetClass, "Oh my god.");
	String expected = "Input: Oh my god.";

	// Assert
	assertEquals(expected, actual);
}

Recommended Posts

Test private methods in JUnit
Test private methods in JUnit
[Java] Test private methods with JUnit
About validation methods in JUnit
How to test private methods with arrays or variadic arguments in JUnit
If you want to satisfy the test coverage of private methods in JUnit
Output JUnit test report in Maven
Things to keep in mind when testing private methods in JUnit
How to filter JUnit Test in Gradle
Refactoring in JUnit
How to test private scope with JUnit
JUnit 5: How to write test cases in enum
Visualize test methods running in TestNG with listeners
Mixin test cases with JUnit 5 and default methods
Unit test with Junit.
Get the name of the test case in the JUnit test class
Implement test doubles in JUnit without using external libraries
[Java] JUnit4 test case example
Test Web API with junit
Dynamically call methods in JSF
Helper methods available in devise
Check Java9 Interface private methods
[JUnit] Test the thrown exception
Mock static methods in Mockito 3.4
[Spring Boot] Until @Autowired is run in the test class [JUnit5]
Implement Table Driven Test in Java 14
About methods often used in devise
JUnit 5 parameterization test is super convenient
Differences in split methods of StringUtils
Test API often used in AssertJ
Frequently used methods in Active Record
What are the rules in JUnit?
Test Spring framework controller with Junit
Ruby methods often used in Rails
How to test a private method in Java and partially mock that method