我正在尝试为以下 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。文件(字节[]文件内容,字符串内容类型,字符串文件下载名称)
我不明白这里出了什么问题。请指教。
LEATH
相关分类