Mocking a class in PowerMock

我只是一个虾纸丫 提交于 2019-12-11 19:42:34

问题


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

I want to mock one class which is non static.

The class scenario goes as follows.

 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) {


    }

}

The calling class is as follows.

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

The Question is,

I am trying to test the above class using powermock.

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


回答1:


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.
    }

}



回答2:


Here is a description of how to mock a constructor call: MockConstructor



来源:https://stackoverflow.com/questions/18869176/mocking-a-class-in-powermock

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!