为了账号安全,请及时绑定邮箱和手机立即绑定

在单元测试中返回 FileContentResult 时,Http 响应标头解析器失败

在单元测试中返回 FileContentResult 时,Http 响应标头解析器失败

C#
紫衣仙女 2023-08-13 16:16:43
我正在尝试为以下 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);}文件内容类: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}在以下控制器线路上测试失败:return File(file.File, file.ContentType);例外情况:System.FormatException:标头在索引 0 处包含无效值:“文件内容”。在 Microsoft.Net.Http.Headers.HttpHeaderParser`1.ParseValue(StringSegment value, Int32& index) 在 Microsoft.AspNetCore.Mvc.FileContentResult..ctor(Byte[] fileContents, String contentType) 在 Microsoft.AspNetCore.Mvc.ControllerBase。文件(字节[]文件内容,字符串内容类型,字符串文件下载名称)我不明白这里出了什么问题。请指教。
查看完整描述

1 回答

?
LEATH

TA贡献1936条经验 获得超6个赞

当您向响应添加标头时,ASP.NET Core 将验证已知标头以确保它们包含有效值。在您的情况下,您尝试将内容类型设置为"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,因此该值的验证失败。

相反,您应该使用实际的 MIME 类型,例如,text/plain因为您的测试中还有纯文本内容:

repositoryMock
    .Setup(x => x.GetFile(It.IsAny<string>(), null))
    .ReturnsAsync(new FileContent("test.txt", "text/plain", Encoding.UTF8.GetBytes("File Content.")));



查看完整回答
反对 回复 2023-08-13
  • 1 回答
  • 0 关注
  • 57 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信