[英]Constructor suppressing not working with PowerMock+Mockito
I have a class that implements singleton as 我有一类实现单例为
public class UMR {
private static UMR umr = new UMR();
private MR mr;
private UMR(){
this.mr = MR.getInstance();
}
public static UMR getInstance() {
return umr;
}
}
and here is my test method code 这是我的测试方法代码
@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");
}
annotations used and imports: 使用和导入的注释:
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})
I do not want the private constructor to be called but it still calls the constructor even after suppressing the constructor successfully in first statement. 我不希望调用私有构造函数,但是即使在第一个语句中成功抑制了构造函数之后,它仍然会调用构造函数。
Please suggest if I am doing anything wrong. 请建议我是否做错了什么。
An constructor in this line is called before the constructor is suppressed. 在抑制该构造函数之前,将调用此行中的构造函数。
private static UMR umr = new UMR()
You have to use the @SuppressStaticInitializationFor
in this case. 在这种情况下,您必须使用@SuppressStaticInitializationFor
。
Could you move to a lazy initialising singleton pattern? 您可以转到懒惰的初始化单例模式吗?
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.