Настройка HttpContent.ReadAsStreamAsync для модульных тестов - PullRequest
0 голосов
/ 05 декабря 2018

Я пытаюсь смоделировать метод, который использует HttpContent.ReadAsStreamAsync () в качестве одного из входных параметров.Я пытаюсь проверить, был ли этот метод вызван с ожидаемым параметром «System.IO.Stream», но «verify» завершается неудачно, так как тестовый запуск был вызван параметром «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;
    }
}

Сбой при "Подтвердить""line (раздел Assert), говорящий, что вызов произошел с параметром" ReadOnlyStream ", но он был проверен с параметром" MemoryStream ".

Ниже приведено сообщение об ошибке от организатора теста.

Сообщение: Moq.MockException:
Ожидаемый вызов на макете один раз, но был 0 раз: s => s.Upload("file", MemoryStream)

Настроенные настройки:
IProcessRepo s => s.Upload(It.IsAny<String>(), It.IsAny<Stream>())

Выполненные вызовы:
IProcessRepo.Upload("file", ReadOnlyStream)

...