我有一个将单例实现为
的类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})
我不希望调用私有构造函数,但即使在第一个语句中成功压缩构造函数后它仍然会调用构造函数。
如果我做错了,请建议。
答案 0 :(得分:0)
在构造函数被抑制之前调用此行中的构造函数。
SELECT st.StudentLastName, stc.CourseDate, c.CourseTitle,
CASE WHEN stc.CourseDate IN (
SELECT AbsenceDate FROM FactAbsence WHERE studentID = stc.StudentID
) THEN'missing'
ELSE 'attended'
END date_info
FROM dimStudent st JOIN
factStudentCourse stc ON st.StudentID = stc.StudentID JOIN
dimCourse c ON stc.CourseID=c.CourseID
ORDER BY stc.CourseDate DESC;
在这种情况下,您必须使用private static UMR umr = new UMR()
。
答案 1 :(得分:-1)
你可以转向懒惰的初始单身模式吗?
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;
}
}