package com.practice;
import
java.lang.reflect.InvocationTargetException;
import
java.lang.reflect.Method;
import
java.util.ArrayList;
import java.util.List;
import
junit.framework.Assert;
import
org.junit.Before;
import org.junit.Test;
public class
ClassWithPrivateMethod {
public static void main(String[]
args) {
// ....
}
private void findOwnerForThisAddress(List<People>
peopleList, Address address) {
// Some logic find out who out of
peopleList stays in this address.
}
}
class People {
}
class Address {
}
JUnit test class to test the private method:
class
PrivateMethodTest {
ClassWithPrivateMethod classOfInterest;
@Before
public void setUp() throws Exception {
classOfInterest = new
ClassWithPrivateMethod();
}
@Test
public void
testFindOwnerForThisAddress() {
Address address = new Address();
List<People> peopleList = new
ArrayList<People>();
try {
Method methodOfInterest;
methodOfInterest =
ClassWithPrivateMethod.class.getDeclaredMethod("findOwnerForThisAddress", List.class, Address.class);
methodOfInterest.setAccessible(true);
methodOfInterest.invoke(classOfInterest, peopleList,
address);
} catch
(SecurityException e) {
Assert.fail(e.getMessage());
} catch
(NoSuchMethodException e) {
Assert.fail(e.getMessage());
} catch
(IllegalArgumentException e) {
e.printStackTrace();
Assert.fail(e.getMessage());
} catch
(IllegalAccessException e) {
Assert.fail(e.getMessage());
} catch
(InvocationTargetException e) {
e.printStackTrace();
Assert.fail(e.getMessage());
}
}
}
Have you seen dp4j? I think it offers a neater solution.
ReplyDelete