我正在嘗試為以下 AspNetCore 控制器方法編寫(xiě)單元測(cè)試:[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; }}這是測(cè)試初始化:[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()));}及測(cè)試方法:[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}在以下控制器線路上測(cè)試失?。簉eturn File(file.File, file.ContentType);例外情況:System.FormatException:標(biāo)頭在索引 0 處包含無(wú)效值:“文件內(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)容類型,字符串文件下載名稱)我不明白這里出了什么問(wèn)題。請(qǐng)指教。
1 回答

LEATH
TA貢獻(xiàn)1936條經(jīng)驗(yàn) 獲得超7個(gè)贊
當(dāng)您向響應(yīng)添加標(biāo)頭時(shí),ASP.NET Core 將驗(yàn)證已知標(biāo)頭以確保它們包含有效值。在您的情況下,您嘗試將內(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àn)證失敗。
相反,您應(yīng)該使用實(shí)際的 MIME 類型,例如,text/plain
因?yàn)槟臏y(cè)試中還有純文本內(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)注
- 132 瀏覽
添加回答
舉報(bào)
0/150
提交
取消