有一次問同事:除了用JAVA Reflection 來測試私有方法外,還有什么好的方法可以更簡單的測試私有方法。
同事回答,可以用Guava的VisibleForTesting。於是看了看這個注釋的用法。
這個注釋的接口定義如下:
@GwtCompatible
public @interface VisibleForTesting
Annotates a program element that exists, or is more widely visible than otherwise necessary, only for use in test code.
從字面上可以被這樣理解: 注釋一個已經存在的程序元素或者所注釋的元素被給於它所必須的更寬松的 可見性,僅僅被使用在測試代碼中。
我們通過一個測試私有方法的例子來看看這個注釋的使用:
1 public class PrivateData { 2 @VisibleForTesting 3 /*private*/ void testPrivate(int pr){ 4 System.out.print(pr); 5 } 6 }
下面是測試類:
1 public class PrivateDataTest { 2 @Test 3 public void testPrivate() throws Exception { 4 PrivateData pm = new PrivateData(); 5 pm.testPrivate(1); 6 } 7 8 }
通過上面的代碼看出, 被測試的testPrivate方法的可見性還是被改成Protected。也就是,VisibleForTesting只是一個注釋,一個元數據metadata,它並沒有進入程序邏輯,也沒有被轉化成字節碼byte code 從而被JVM執行。
筆者猜測可能是Guava 的 程序員犯懶了, 即不願意在unit test里直接利用Reflection來測試私有方法。也沒有把私有方法寫入另一個類中。所以設計了VisibleForTesting的注解來提醒其他程序員: 這里為了測試私有方法把私有方法改成了Protected(受保護的)並放寬了訪問限制。
可是就JAVA本身而言,只有通過Reflection才能真正測試私有方法。
