在PowerMock中模拟课程 [英] Mocking a class in PowerMock

查看:77
本文介绍了在PowerMock中模拟课程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将PowerMocking用于JUNIT,而Iam是PowerMock的新功能.

I am using PowerMocking for JUNIT and Iam new to PowerMock.

我想模拟一个非静态的类.

I want to mock one class which is non static.

课堂情况如下.

 public class Export extends MyUtil implements ExportFormatting<DeptSummaryByDCDTO, LmReportsInputDTO>{

    public String createPDF(List<DeptSummaryByDCDTO> summaryDtoList, LmReportsInputDTO inputDto){

     }

    public String createPDF(Map<String, DeptSummaryByDCDTO> paramMap,
        LmReportsInputDTO paramK) {


    }

}

调用类如下.

 public static Response getMultiplePackSku{
       filePath = new Export(inputDto).createPDF(resultList,null);
 }

问题是

我正在尝试使用powermock测试以上课程.

I am trying to test the above class using powermock.

任何人都可以告诉我们如何模拟 filePath .....

Can anybody tell how to mock the line filePath.....

推荐答案

您需要先模拟构造函数并返回Export模拟.在返回的模拟中,您需要记录对createPDF的调用.棘手的部分是构造函数模拟.我给你举个例子,希望你能得到全部:

You need to first mock the constructor and return an Export mock. On the returned mock you need to record the call to createPDF. The tricky part is the constructor mocking. I'll give you an example, hopefully you'll get all of it:

@RunWith(PowerMockRunner.class) // This annotation is for using PowerMock
@PrepareForTest(Export.class) // This annotation is for mocking the Export constructor
public class MyTests {

    private mockExport;

    @Before
    public void setUp () {
        // Create the mock
        mockExport = PowerMock.createMock(Export.class)
    }

    @Test
    public void testWithConstructor() {
        SomeDtoClass inputDto = PowerMock.createMock(SomeDtoClass.class); 
        PowerMock.expectNew(Export.class, inputDto).andReturn(mockExport);
        PowerMock.replay(mockExport, Export.class);
        expect(mockExport.createPDF(resultList, null);


        // Run the tested method.
    }

}

这篇关于在PowerMock中模拟课程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆