[英]Constructor suppressing not working with PowerMock+Mockito
我有一類實現單例為
public class UMR {
private static UMR umr = new UMR();
private MR mr;
private UMR(){
this.mr = MR.getInstance();
}
public static UMR getInstance() {
return umr;
}
}
這是我的測試方法代碼
@Test
public void test(){
suppress(constructor(UMR.class));
mockStatic(UMR.class);
UMR umr = PowerMockito.mock(UMR.class);
when(UMR.getInstance()).thenReturn(umr);
System.out.println("End");
}
使用和導入的注釋:
import static org.powermock.api.mockito.PowerMockito.mockStatic;
import static org.powermock.api.mockito.PowerMockito.when;
import static org.powermock.api.support.membermodification.MemberMatcher.constructor;
import static org.powermock.api.support.membermodification.MemberModifier.suppress;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
@RunWith(PowerMockRunner.class)
@PrepareForTest({UMR.class})
我不希望調用私有構造函數,但是即使在第一個語句中成功抑制了構造函數之后,它仍然會調用構造函數。
請建議我是否做錯了什么。
在抑制該構造函數之前,將調用此行中的構造函數。
private static UMR umr = new UMR()
在這種情況下,您必須使用@SuppressStaticInitializationFor
。
您可以轉到懶惰的初始化單例模式嗎?
public class UMR {
private static UMR umr;
private MR mr;
private UMR(){
this.mr = MR.getInstance();
}
public static UMR getInstance() {
// double locked lazy initializing singleton
if (umr==null) {
synchronized(UMR.class) {
// when we get here, another thread may have already beaten us
// to the init
if(umr==null) {
// singleton is made here on first use via the getInstance
// as opposed to the original example where the singleton
// is made when anything uses the type
umr = new UMR();
}
}
}
return umr;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.