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

Sim*_*onD 3 c# unit-testing asp.net-core

我正在尝试为以下 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);
}
Run Code Online (Sandbox Code Playgroud)

文件内容类:

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; }
}
Run Code Online (Sandbox Code Playgroud)

这是测试初始化​​:

[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()));
}
Run Code Online (Sandbox Code Playgroud)

及测试方法:

[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
}
Run Code Online (Sandbox Code Playgroud)

在以下控制器线路上测试失败:

return File(file.File, file.ContentType);
Run Code Online (Sandbox Code Playgroud)

例外情况:

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。文件(字节[]文件内容,字符串内容类型,字符串文件下载名称)

我不明白这里出了什么问题。请指教。

pok*_*oke 5

当您向响应添加标头时,ASP.NET Core 将验证已知标头以确保它们包含有效值。在您的情况下,您尝试将内容类型设置为"File Content."此处:

\n\n
repositoryMock\n    .Setup(x => x.GetFile(It.IsAny<string>(), null))\n    .ReturnsAsync(new FileContent("test.txt", "File Content.", Encoding.UTF8.GetBytes("File Content.")));\n//                                            \xe2\x86\x91\xe2\x86\x91\xe2\x86\x91\xe2\x86\x91\xe2\x86\x91\xe2\x86\x91\xe2\x86\x91\xe2\x86\x91\xe2\x86\x91\xe2\x86\x91\xe2\x86\x91\xe2\x86\x91\xe2\x86\x91\xe2\x86\x91\xe2\x86\x91\n
Run Code Online (Sandbox Code Playgroud)\n\n

File Content.不是有效的MIME type,因此该值的验证失败。

\n\n

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

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