如何验证是否调用了printPreview.createShowReport();
。我什至无法设置模拟对象,因为一旦我调用该方法,它就会实例化为 null 并创建新对象。
public void previewOrDirectPrint(File file, boolean val) {
try{
printPreview=null;
printPreview=new ExamReportPrintUI(this,file);
}
catch(Exception e){
e.printStackTrace();
}
if(!val)
{
printPreview.createShowReport();
}
else
{
printPreview.createHideReport();
printInitiate();
closeReportPreview();
}
here is my test case
@Test
public void testpreviewOrDirectPrint()
{
File file=new File("/Desktop/config/reportTemplate.html");
examReportManager.previewOrDirectPrint(file, false);
assertNotNull(Whitebox.getInternalState(examReportManager, "printPreview"));
}
Can anyone help me how to access the object or create mock and set to it. I can only verify if the object is mock.
我尝试使用Whitebox.setInternalstate("obj","",mockobject).
进行设置,但两个对象都不同。
不使用PowerMockito的解决方案如下:
1( 添加一个负责返回 ExamReportPrintUI
实例的方法,并更改正在测试的方法以这种方式获取该实例:
public void previewOrDirectPrint(File file, boolean val) {
try{
printPreview=null;
printPreview= getExamReportInstance(this,file);
}
...
}
ExamReportPrintUI getExamReportInstance(ExamReportManager e, File f){
return new ExamReportPrintUI(e,f);
}
2( 监视管理器并模拟 getExamReportInstance 方法以返回所需的模拟:
@Test
public void testpreviewOrDirectPrint()
{
ExamReportManager spyManager = Mockito.spy(examReportManager);
doReturn(examReportPrintUIMock).when(spyManager).getExamReportInstance(Mockito.any(ExamReportManager.class), Mockito.any(File.class));
File file=new File("/Desktop/config/reportTemplate.html");
examReportManager.previewOrDirectPrint(file, false);
assertNotNull(Whitebox.getInternalState(examReportManager,printPreview"));
}
现在,您可以控制该类的实例,并且可以注入配置的模拟。
与PowerMockito
@RunWith(PowerMockRunner.class)
@PrepareForTest(ExamReportPrintUI.class)
public ExamReportManagerTest{
@Mock
ExamReportPrintUI examReportPrintUIMock;
@Test
public void testpreviewOrDirectPrint()
{
PowerMockito.whenNew(examReportPrintUI.class)
.withArguments(Mockito.any(ExamReportManager.class), Mockito.any(File.class))
.thenReturn(examReportPrintUIMock);
File file=new File("/Desktop/config/reportTemplate.html");
examReportManager.previewOrDirectPrint(file, false);
assertNotNull(Whitebox.getInternalState(examReportManager, "printPreview"));
}
}