[英]Which is better, Java reflection or extend class in test
有一個我要為其編寫JUnit測試的Java類。
使用JaCoCo監視代碼覆蓋率。 因此,還需要從測試類中調用私有方法。
使用Java反射從測試類中調用主方法和私有方法。
我的問題是更好地擴展測試類中的主類(示例),還是使用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);
}
}
不要使用反射來測試私有方法,最好通過使用公共方法來測試這些方法。
因此,在這種情況下,請使用Example.main()
測試基礎方法。
理想情況下,您將重構代碼以將需要自己測試的private
方法提取到新類中的新public
方法中。 如果功能需要單獨的測試,則通常可以視為public
。
除了使用反射,您還可以將這些方法的可見性更改為默認級別,並且同一程序包中的測試將可以使用它們。
public class Example {
Employee method1(String str) {
...
}
Employee method2(String str1) {
...
}
}
public class ExampleTest {
@Test
public void testMethod1() {
new Example().method1(...);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.