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