简体   繁体   中英

PowerMockito mocking static testing controller in spring 3.2.4

I am performing some mockito test, but I have some problems with 1 class that have an static method, that I Mocked up in the setUp() method of the test class

Having this class:

public class ResponseFileWriteHelper {


    public static void write(HttpServletResponse response, String fileName, StreamWriter writer) {

        response.setHeader("Cache-Control", "");
        response.setContentType("application/octet");
        if (!StringUtils.isBlank(fileName)) {
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
        }

        try {
            writer.doWrite(response.getOutputStream());
        }
        catch (Exception e) {
            throw new RuntimeException(e);
        }    
    }
}

Here the controller I want to test:

public class ManageDeviceController extends SimpleFormController {

...

private void generateDevicexBeneficiaryList(
            Collection<Integer> selectedYears, PriorityAreaKey priorityAreaKey, Language language, Collection<DeviceStatus> statuses, HttpServletResponse response) throws Exception {

        final List<ReportItem> reportItems
            = DeviceListReportService.getDevicesxBeneficiaryForYears(selectedYears, priorityAreaKey, language, statuses);

        ResponseFileWriteHelper.write(response, "DevicesxBeneficiaryList.xls", new StreamWriter() {

            @Override
            public void doWrite(OutputStream outputStream) throws Exception {
                DeviceListExcelReportRendererBuilder.build().renderToStream(
                    reportItems, outputStream);
            }});
    }

}

Here the test class

@RunWith(MockitoJUnitRunner.class)
public class SelectDeviceListExcelReportControllerTest {

    public void setUp() {
        PowerMockito.mockStatic (ResponseFileWriteHelper.class);
        EDeviceSessionContext.getInstance().setSession(httpSession);
        when(request.getSession()).thenReturn(httpSession);
        when(request.getLocale()).thenReturn(Locale.ENGLISH);
        messages.initialize();
    }

    @SuppressWarnings("unchecked")
    @Test
    @PrepareForTest(ResponseFileWriteHelper.class)
    public void successTest() throws Exception {

        TableItemBuilder tableItemBuilder = 
                new TableItemBuilder(new LabelCellItem("success.test"));

        List<ReportItem> expectedData = Arrays.asList(
            new ReportItem("success.test",Arrays.asList(tableItemBuilder.getTableItem())));

        final ByteArrayOutputStream resultData = new ByteArrayOutputStream();

        ServletOutputStream output = new ServletOutputStream() {

            @Override
            public void write(int val) throws IOException {
                resultData.write(val);
            }
        };

        when(response.getOutputStream()).thenReturn(output);

        when(deviceListReportService.getDevicesxBeneficiaryForYears(
            any(List.class), any(PriorityAreaKey.class), any(Language.class), any(Collection.class))).thenReturn(expectedData);


        doCall();

        //assertArrayEquals(expectedData, resultData);
    }
}

But the test crashes because a java.lang.NullPointer here:

ResponseFileWriteHelper.write(response, "DevicesxBeneficiaryList.xls", new StreamWriter() {

The @PrepareForTest() in only working with PowerMockRunner.class in your test class, so you need add the @RunWith(PowerMockRunner.class) in your test class.

But it comes another problem is that you really want using SpringJUnit4ClassRunner.class as your test runner, thanks powermock already realize this problem, it provider the PowerMockRunnerDelegate annotation to achieve it.

The working copy will be like that:

@WebAppConfiguration
@ContextConfiguration(locations = {
        "......"
        )
@RunWith(PowerMockRunner.class)
@PowerMockRunnerDelegate(SpringJUnit4ClassRunner.class)
@PowerMockIgnore("javax.management.*") // to specify that all classes under the specified package be loaded by the system class loader
@PrepareForTest({Static.class})
public void ControllerTest {
    public void testMockStatic() {
        PowerMockito.mockStatic(Static.class);
        ......
    }
}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM