0
我不確定爲什麼會發生這種情況,但是當我運行測試代碼時,出現OutOfMemoryException異常。Powermockito在存根時拋出OutOfMemory異常FileOutputStream
測試:
@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);
}
}
}
非常感謝。我用下面的附加行修復了它:PowerMockito.when(is.read(any(byte []。class)))。thenReturn(1,-1);不知道我是如何錯過它的.. – sethu 2013-03-25 15:45:33