我正在尝试模拟一种使用HttpContent.ReadAsStreamAsync()作为输入参数之一的方法。我正在尝试验证是否使用预期的“ System.IO.Stream”参数调用了此方法,但是“验证”失败,因为使用“ ReadOnlyStream”参数调用了测试运行,但是使用“ MemoryStream”参数进行了验证。我正在使用NUnit和Moq。我在下面粘贴了源代码和单元测试的可演示版本。请帮忙。预先感谢。
源代码
public class TestController: ApiController
{
private readonly IProcessRepo _repo;
public TestController(IProcessRepo repo)
{
_repo = repo;
}
[HttpGet]
public async Task<IHttpActionResult> GetRecords()
{
var streamProvider = await Request.Content.ReadAsMultipartAsync();
foreach (var postedFile in streamProvider.Contents)
{
var result = _repo.Upload("file", await postedFile.ReadAsStreamAsync());
}
return Ok();
}
}
public class ProcessRepo: IProcessRepo
{
public bool Upload(string type, Stream contentStream)
{
//Upload Code here
return true;
}
}
public interface IProcessRepo
{
bool Upload(string type, Stream contentStream);
}
单元测试
[TestFixture]
public class TestControllerTests
{
[Test]
public async Task RunTest()
{
//Arrange
var mockProcessRepo = new Mock<IProcessRepo>();
var controller = new TestController(mockProcessRepo.Object);
mockProcessRepo.Setup(s => s.Upload(It.IsAny<string>(), It.IsAny<Stream>())).Returns(true);
HttpRequestMessage request = new HttpRequestMessage();
byte[] fileContents = GenerateRandomByteArray();
Stream memStream = new MemoryStream(fileContents, false);
MultipartFormDataContent multiPartContent = new MultipartFormDataContent("----MyGreatBoundary");
ByteArrayContent byteArrayContent = new ByteArrayContent(fileContents);
byteArrayContent.Headers.Add("Content-Type", "application/octet-stream");
multiPartContent.Add(byteArrayContent, "Bundle");
request.Content = multiPartContent;
controller.Request = request;
controller.Request.SetConfiguration(new HttpConfiguration());
//Act
var response = await controller.GetRecords();
//Assert
mockProcessRepo.Verify(s => s.Upload("file", memStream), Times.Once);
}
private byte[] GenerateRandomByteArray()
{
byte[] fileContents = new byte[20];
(new Random()).NextBytes(fileContents);
return fileContents;
}
}
它在“验证”行(“声明”部分)失败,表示调用是通过“ ReadOnlyStream”参数发生的,但已通过“ MemoryStream”参数进行了验证。
下面是来自测试运行程序的错误消息。
消息:Moq.MockException:
预期对该模拟调用一次,但为0次:s => s.Upload("file", MemoryStream)
配置的设置:
IProcessRepo s => s.Upload(It.IsAny<String>(), It.IsAny<Stream>())
执行的调用:
IProcessRepo.Upload("file", ReadOnlyStream)