Have a Java class for which, I am trying to write a JUnit test.
Using JaCoCo to monitor code coverage. Hence, need to call private methods as well from test class.
To call main method and private methods from test class using Java reflection.
My question is extending the main class (Example) in test class better or using java reflection to access the private methods? Currently I am using the reflection as below.
Is it even a good practice to extend the Java class in test class?
I am new to writing test class hence, the question. I would appreciate your help on this.
public class Example {
public static void main(String[] s) {
method1();
method2();
..........
}
private Employee method1(String str) {
.........
}
private Employee method2(String str1) {
.........
}
}
public class ExampleTest {
@InjectMocks
Example example;
.....
@Before
public void setUp() {
........
}
@Test
public void testMain() {
try {
String[] addresses = new String[]{};
Example loadSpy = spy(example);
loadSpy.main(addresses);
assertTrue(Boolean.TRUE);
} catch (.. e) {
.......
}
assertTrue(true);
}
@Test
public void testMethod1() {
try {
Method method = example.getClass().getDeclaredMethod("method1", String.class);
method.setAccessible(true);
method.invoke(example, "1111");
} catch (Exception e) {
.....
}
assertTrue(true);
}
@Test
public void testMethod1() {
try {
Method method = example.getClass().getDeclaredMethod("method2", String.class);
method.setAccessible(true);
method.invoke(example, "1111");
} catch (Exception e) {
.....
}
assertTrue(true);
}
}