如何单元测试Java的private方法
生活随笔
收集整理的這篇文章主要介紹了
如何单元测试Java的private方法
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
問題
Java類中private方法通常只能被其所屬類的調(diào)用,其他類只能望而卻步,單元測試private方法也就一籌莫展。
嘗試解法:
上述解法雖然可行,但這些解法或多或少地違背單元測試應(yīng)遵守AIR原則。
單元測試在線上運(yùn)行時(shí),感覺像空氣(AIR)那樣透明,但在測試質(zhì)量的保障上,卻是非常關(guān)鍵的。好的單元測試宏觀上來說,具有自動化、獨(dú)立性、可重復(fù)執(zhí)行的特點(diǎn)。
- A:Automatic(自動化)
- I:Independent(獨(dú)立性)
- R:Repeatable(可重復(fù))
解法
先創(chuàng)建一個(gè)測試目標(biāo)類App作為示例,目標(biāo)是測試App類中private方法callPrivateMethod():
public class App {public void doSomething() {callPrivateMethod();}private String callPrivateMethod() {return "Private method is called.";}}一
我們可以用Java的反射特性來突破private的限制,從而對private方法進(jìn)行單元測試:
單元測試代碼:
import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method;import org.junit.Assert; import org.junit.Test;public class AppTest {@Testpublic void test() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {App app = new App();Method privateMethod = app.getClass().getDeclaredMethod("callPrivateMethod");privateMethod.setAccessible(true);Assert.assertEquals("Private method is called.", privateMethod.invoke(app));} }二
引入第三方工具,如Spring測試框架。
引入依賴:
<dependency><groupId>org.springframework</groupId><artifactId>spring-test</artifactId><version>5.3.5</version><scope>test</scope> </dependency>單元測試代碼:
import static org.junit.Assert.*;import org.junit.Test; import org.springframework.test.util.ReflectionTestUtils;public class AppTest {@Testpublic void test() {App app = new App();assertEquals("Private method is called.", //ReflectionTestUtils.invokeMethod(app, "callPrivateMethod", null));}}參考
總結(jié)
以上是生活随笔為你收集整理的如何单元测试Java的private方法的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: textCNN初探
- 下一篇: Java中<? super T>和Lis