我嘗試對接收具有 HttpPostedFile 作為引數的模型的 mvc 控制器進行單元測驗
var constructorInfo = typeof(HttpPostedFile).GetConstructors(BindingFlags.NonPublic | BindingFlags.Instance)[0];
var obj = (HttpPostedFile)constructorInfo
.Invoke(new object[] { @"D:\test.xlsx", "application/vnd.ms-excel", null });
model.MembershipRegisterFile = new HttpPostedFileWrapper(obj);
當我運行測驗并且控制器嘗試將檔案保存到磁盤時,我在這一行得到一個例外..
file.SaveAs(完整路徑);
有錯誤...
System.NullReferenceException: 'Object reference not set to an instance of an object.'
我認為這是因為檔案沒有真正上傳并且檔案的內容長度為空。那么我應該如何處理這個問題。我應該在我的控制器內部有邏輯內容長度等于 null 的可能性還是 HttpPostedFile 可以設定內容長度?
更新:我像這樣嘲笑檔案,這很有效....
var postedfile = new Mock<HttpPostedFileBase>();
postedfile.Setup(f => f.ContentLength).Returns(8192);
postedfile.Setup(f => f.FileName).Returns("myfile.txt");
postedfile.Setup(f => f.InputStream).Returns(new MemoryStream(8192));
myObject.HttpPostedFile = postedfile.Object;
uj5u.com熱心網友回復:
單元測驗檔案 I/O 你可以分析鏈接。我認為您不應該在專案中放置檔案。您應該創建一個模擬檔案。創建模擬檔案使用 System.IO.Abstractions
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/483523.html
標籤:C# 单元测试 httppostedfile
下一篇:用字串陣列填充資料表
