[英]how to mock private static inner class?
我有一個像
public class Enclosing {
public String methodA() {
Inner.getContext();
......
}
private static class Inner{
// some context init
public static Context getContext() {
.....
}
}
}
現在,我想在不調用真正的Inner.getContext()的情況下測試methodA。 我一直在搜索,但找不到有效的解決方案。 我正在使用Java8。請給我一些幫助嗎? 非常感謝
您可以應用擴展和覆蓋技術 ,這是它的工作原理。
給出以下代碼:
public class Enclosing {
public String methodA() {
Inner.getContext();
......
}
您可以將Inner.getContext()
調用移至protected
方法:
public class Enclosing {
public String methodA() {
getContext();
......
}
protected void getContext() {
Inner.getContext();
......
}
然后在測試用例中,您可以擴展封閉的類,並覆蓋protected
方法以對其進行任何處理:
@Test
public void test_something() {
Enclosing enclosing = new Enclosing() {
@Override
protected void getContext() {
// do what you need here
}
};
// your test code on enclosing where you control getContext
}
作為@janos答案的替代方法,您可以插入一個策略 (基本上是“優先考慮繼承而不是繼承”):
interface ContextStrategy {
void getContext();
}
然后將其實例注入Enclosing
的構造函數中:
class Enclosing {
private final ContextStrategy ctxStrategy;
Enclosing(ContextStrategy ctxStrategy) {
this.ctxStrategy = ctxStrategy;
}
String methodA() {
ctxStrategy.getContext();
// ...
}
}
然后針對生產案例實現此接口,作為Enclosing
的嵌套類:
static class ContextStrategyImpl implements ContextStrategy {
@Override public void getContext() {
Inner.getContext();
}
}
並為您的模擬案例實現替代版本。
你不應該嘲笑一個private
類(無論是喜歡這里的一個或一個實際的內部類嵌套類)。
相反,僅模擬確實需要的Context
類型(否則,使用真實的Context
對象)。 例如,下面使用JMockit庫顯示了這樣的測試:
@Test
public void mockingTheContext(@Mocked Context anyContext) {
new Expectations() {{
// record any method call results expected from "anyContext"
}};
new Enclosing().methodA();
new Verifications() {{
// verify calls to "anyContext", if applicable
}};
}
在上面的測試中,在嵌套類內部創建Context
是無關緊要的。 通常,應始終避免嘲笑private
方法或類,因為它們只是實現細節。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.