0

我不确定为什么会发生这种情况,但是当我运行测试代码时,我得到了 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);
        }
    }
}
4

1 回答 1

2

IOUtils.copy的源代码包含一个循环,如果您InputStream未能从其read()方法返回值“-1”,该循环将永远不会终止。

我猜想你的模拟默认情况下会从int返回类型的方法返回“0”,所以你的测试代码进入一个无限循环,无限循环地将 4k 大小的字节数组写入OutputStream.

于 2013-03-25T15:30:21.123 回答