我正在嘗試為以下 AspNetCore 控制器方法編寫單元測試:[HttpGet]public async Task<IActionResult> GetFile(string id){ FileContent file = await fileRepository.GetFile(id); if (file == null) return NotFound(); Response.Headers.Add("Content-Disposition", file.FileName); return File(file.File, file.ContentType);}文件內(nèi)容類:public class FileContent{ public FileContent(string fileName, string contentType, byte[] file) { FileName = fileName; ContentType = contentType; File = file; } public string FileName { get; } public string ContentType { get; } public byte[] File { get; }}這是測試初始化:[TestInitialize]public void TestInitialize(){ repositoryMock = new Mock<IFileRepository>(); controller = new FilesController(repositoryMock.Object); var httpContext = new Mock<HttpContext>(MockBehavior.Strict); var response = new Mock<HttpResponse>(MockBehavior.Strict); var headers = new HeaderDictionary(); response.Setup(x => x.Headers).Returns(headers); httpContext.SetupGet(x => x.Response).Returns(response.Object); controller.ControllerContext = new ControllerContext(new ActionContext(httpContext.Object, new RouteData(), new ControllerActionDescriptor()));}及測試方法:[TestMethod]public async Task GetShouldReturnCorrectResponse(){ repositoryMock .Setup(x => x.GetFile(It.IsAny<string>(), null)) .ReturnsAsync(new FileContent("test.txt", "File Content.", Encoding.UTF8.GetBytes("File Content."))); IActionResult response = await controller.GetFile(DocumentId); // .. some assertions}在以下控制器線路上測試失?。簉eturn File(file.File, file.ContentType);例外情況:System.FormatException:標頭在索引 0 處包含無效值:“文件內(nèi)容”。在 Microsoft.Net.Http.Headers.HttpHeaderParser`1.ParseValue(StringSegment value, Int32& index) 在 Microsoft.AspNetCore.Mvc.FileContentResult..ctor(Byte[] fileContents, String contentType) 在 Microsoft.AspNetCore.Mvc.ControllerBase。文件(字節(jié)[]文件內(nèi)容,字符串內(nèi)容類型,字符串文件下載名稱)我不明白這里出了什么問題。請指教。
1 回答

LEATH
TA貢獻1936條經(jīng)驗 獲得超7個贊
當您向響應(yīng)添加標頭時,ASP.NET Core 將驗證已知標頭以確保它們包含有效值。在您的情況下,您嘗試將內(nèi)容類型設(shè)置為"File Content."
此處:
repositoryMock ????.Setup(x?=>?x.GetFile(It.IsAny<string>(),?null)) ????.ReturnsAsync(new?FileContent("test.txt",?"File?Content.",?Encoding.UTF8.GetBytes("File?Content."))); ????//????????????????????????????????????????????↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑
但File Content.
不是有效的MIME type,因此該值的驗證失敗。
相反,您應(yīng)該使用實際的 MIME 類型,例如,text/plain
因為您的測試中還有純文本內(nèi)容:
repositoryMock ????.Setup(x?=>?x.GetFile(It.IsAny<string>(),?null)) ????.ReturnsAsync(new?FileContent("test.txt",?"text/plain",?Encoding.UTF8.GetBytes("File?Content.")));
- 1 回答
- 0 關(guān)注
- 123 瀏覽
添加回答
舉報
0/150
提交
取消