其他分享
首页 > 其他分享> > 嘲笑一个CloudBlockBlob,并使其返回流

嘲笑一个CloudBlockBlob,并使其返回流

作者:互联网

我正在尝试对Azure CloudBlockBlob进行Moq并让其返回流,以便可以测试BlobStorage存储库是否正确处理了输出.
但是以某种方式返回的流始终为空.

单元测试代码:

        ....
        var stream = new MemoryStream();
        var writer = new StreamWriter(stream);
        writer.Write("sample data");
        writer.Flush();
        stream.Position = 0;

        var blobMock = new Mock<CloudBlockBlob>(new Uri("http://tempuri.org/blob"));
        blobMock
            .Setup(m => m.ExistsAsync())
            .ReturnsAsync(true);
        blobMock
            .Setup(m => m.DownloadToStreamAsync(It.IsAny<MemoryStream>()))
            .Returns(Task.FromResult(stream));
        ....

仓库代码:

        ....
        var blob = GetContainer(container).GetBlockBlobReference(name);
        if (await blob.ExistsAsync())
        {
            var ms = new MemoryStream();
            await blob.DownloadToStreamAsync(ms);
            ms.Seek(0, SeekOrigin.Begin);
            return ms;
        }
        ....

因此,我返回的ms流始终是空流,而不是我在Moq Return()方法中使用的流对象.
我如何让该Blob返回我的样本流?

解决方法:

那是两个不同的流.在Callback中获取通过模拟参数传递的流,然后复制测试流.

例如

//....
var stream = new MemoryStream();
var writer = new StreamWriter(stream);
writer.Write("sample data");
writer.Flush();
stream.Position = 0;

var blobMock = new Mock<CloudBlockBlob>(new Uri("http://tempuri.org/blob"));
blobMock
    .Setup(m => m.ExistsAsync())
    .ReturnsAsync(true);
blobMock
    .Setup(m => m.DownloadToStreamAsync(It.IsAny<Stream>()))
    .Callback((Stream target) => stream.CopyTo(target)) //<---Something like this
    .Returns(Task.CompletedTask);
//....

该模拟实际上并不返回流.假定对流进行操作,这就是为什么需要回调来复制预期行为的原因.

记笔记

Copying begins at the current position in the current stream, and does not reset the position of the destination stream after the copy operation is complete.

因此,在这种情况下,如果打算从目标读取,则可能需要重置它

//...

.Callback((Stream target) => {
    stream.CopyTo(target);
    target.Position = 0;
})

//...

标签:asp-net-core,moq,azure-storage,c
来源: https://codeday.me/bug/20191211/2105832.html