如何在单元测试中模拟字节数组中的假文件大小

时间:2019-08-02 11:14:57

标签: c# unit-testing .net-core

在这里,我有将文档复制到特定位置的代码,因为我有如下创建伪造文件的代码。

private static Mock<IFormFile> GetMockFormFile()
{
      var fileMock = new Mock<IFormFile>();
      var fileStreamProviderMock = new Mock<IFileStreamProvider>();
      var contentTypes = "text/plain";
      var content = "Fake File";
      var fileName = "Test.txt";
      var disk = new MemoryStream();
      var writers = new StreamWriter(disk);
      writers.Write(content);
      writers.Flush();
      disk.Position = 0;
      fileMock.Setup(_ => _.OpenReadStream()).Returns(disk);
      fileMock.Setup(_ => _.FileName).Returns(fileName);
      fileMock.Setup(_ => _.Length).Returns(disk.Length);
      fileMock.Setup(_ => _.ContentType).Returns(contentTypes);
      fileMock.Setup(_ => _.ContentDisposition).Returns($"form-data;name='file';filename ='{fileName}'");
      fileStreamProviderMock.Setup(_ => _.Create(It.IsAny<string>())).Returns(disk);
      fileStreamProviderMock.Setup(_ => _.Open(It.IsAny<string>())).Returns(disk);
      fileMock.Setup(_ => _.CopyToAsync(disk, It.IsAny<CancellationToken>())).Returns(Task.CompletedTask);
      fileMock.Verify();
      return fileMock;
}

我正在将这个假文件传递给控制器​​,例如

[Fact]
public async sample()
{
    var formFile = GetMockFormFile();
    var file = formFile.Object;
    var SavedFile = new AttachmentMetadata
    {
        Id = 4231,
        DocumentName = file.FileName,
        DocumentType = file.ContentType,
        CreatedDateTime = dateTime,
        ModifiedDateTime = dateTime
    };
    var viewModel = new AttachmentViewModel()
    {
        File = new List<IFormFile> { file }
    };

    await controller.AddAttachment(viewModel);
    fileStreamProviderMock.Verify(_ => _.Create(@"C:\TestFolder\Test.txt"));
    formFile.Verify(_ => _.CopyToAsync(It.IsAny<Stream>(), It.IsAny<CancellationToken>()));
}

在我的控制器内部,我有一些类似的代码

foreach (var file in model.File)
  {
    using (var ms = new MemoryStream())
       {
            file.CopyTo(ms);
            fileBytes = ms.ToArray();
       } 
  ----
  ----
}

应该返回fileBytes而不是0的东西,目前我将fileBytes设为0,这会导致进一步的代码执行出现问题。 那么,还有其他方法可以模拟这个假字节大小吗?

0 个答案:

没有答案