简体   繁体   English

Spring 3.2.4中的PowerMockito模拟静态测试控制器

[英]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 我正在执行一些模拟测试,但是1类的静态方法存在一些问题,我在测试类的setUp()方法中进行了模拟

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: 但是测试失败,因为这里有一个java.lang.NullPointer:

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. @PrepareForTest()仅与测试类中的PowerMockRunner.class一起使用,因此您需要在测试类中添加@RunWith(PowerMockRunner.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. 但是另一个问题是,您真的想使用SpringJUnit4ClassRunner.class作为测试运行程序,感谢powermock已经意识到了这个问题,它提供了PowerMockRunnerDelegate注释来实现它。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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