哪个更好,Java反射或扩展类测试

opa*_*pai 2 java junit4

有一个Java类,我正在尝试编写一个JUnit测试.

使用JaCoCo监控代码覆盖率.因此,需要从测试类调用私有方法.

使用Java反射从测试类调用main方法和私有方法.

我的问题是更好地扩展测试类中的主类(示例)或使用java反射来访问私有方法?目前我正在使用如下反射.

在测试类中扩展Java类是一个好习惯吗?
因此,我是新编写测试类的问题.我很感激你的帮助.

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

小智 5

不要使用反射来测试私有方法,最好通过使用公共方法来测试这些方法.

所以在这种情况下用于Example.main()测试底层方法.