当存根FileOutputStream时,Powermockito会抛出OutOfMemory异常

时间:2013-03-25 15:23:50

标签: java powermock

我不确定为什么会这样,但是当我运行测试代码时,我得到一个OutOfMemoryException。

测试:

@RunWith(PowerMockRunner.class)
@PrepareForTest(UploadBulkRefundAction.class)
public class UploadBulkRefundActionTest {

    @Mock
    private File file;
    @Mock
    private BulkRefundsForm bulkRefundsForm;
    @Mock
    private FormFile spreadsheetFile;
    @Mock
    private InputStream is;
    @Mock
    private FileOutputStream fileOutputStream;

    @Before
    public void setup() throws Exception {
        PowerMockito.mockStatic(File.class);
        PowerMockito.mockStatic(FileOutputStream.class);
        PowerMockito.mockStatic(IOUtils.class);
        PowerMockito.whenNew(FileOutputStream.class).withArguments(file).thenReturn(fileOutputStream);
    }

    @Test
    public void shouldStoreFileIntoTempFile() throws Exception {
        when(File.createTempFile("tomcat-","bulkrefunds.xlsx")).thenReturn(file);
        when(bulkRefundsForm.getSpreadsheetFile()).thenReturn(spreadsheetFile);
        when(spreadsheetFile.getInputStream()).thenReturn(is);
        UploadBulkRefundAction action=new UploadBulkRefundAction();

        action.execute(null, bulkRefundsForm, null, null);

        verify(spreadsheetFile).getInputStream();
        verifyNew(FileOutputStream.class).withArguments(file);

        verifyStatic();
        File.createTempFile("tomcat-", "bulkrefunds.xlsx");

        verifyStatic();
        IOUtils.copy(is, fileOutputStream);
    }

}

待测班级:

public class UploadBulkRefundAction extends MossoAction {
    @Override
public ActionForward execute(ActionMapping mapping, ActionForm f, HttpServletRequest request, HttpServletResponse response) throws     Exception {
        BulkRefundsForm bulkRefundsForm=(BulkRefundsForm)f;
        File tempFile = storeExcelSheetInATempFile(bulkRefundsForm);
        return null;
    }

    private File storeExcelSheetInATempFile(BulkRefundsForm bulkRefundsForm) throws IOException {
        InputStream inputStream=null;
        FileOutputStream outputStream=null;
        try{
            File tempFile = File.createTempFile("tomcat-", "bulkrefunds.xlsx");
            inputStream = bulkRefundsForm.getSpreadsheetFile().getInputStream();
            outputStream = new FileOutputStream(tempFile);
            IOUtils.copy(inputStream, outputStream);
            return tempFile;
        }finally{
            IOUtils.closeQuietly(inputStream);
            IOUtils.closeQuietly(outputStream);
        }
    }
}

1 个答案:

答案 0 :(得分:2)

source code for IOUtils.copy包含一个循环,如果InputStream无法从read()方法返回值“-1”,该循环将永不终止。

我猜你的mock默认会从int返回类型的方法返回'0',所以你的测试代码进入一个无限循环,无休止地将4k大小的字节数组写入OutputStream