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.
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;
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.