如何模拟CloudBlockBlob ExistsAsync()方法

时间:2019-07-16 12:50:04

标签: .net .net-core moq xunit

我正在使用xUnit和Moq编写单元测试。

我的测试类 TestBlobServiceProvider 构造函数具有以下代码

  private readonly Common.Interfaces.IBlobServiceProvider _iblobprovider;
    public TestBlobServiceProvider()
    {


        var mockCloudBlobContainer = new Mock<IBlobOperations>();
        mockCloudBlobContainer.Setup(repo => repo.parseConnString(It.IsAny<string>())).Returns(new CloudStorageAccount(new StorageCredentials(), new Uri("http://mytest"), new Uri("http://mytest"), new Uri("http://mytest"), new Uri("http://mytest")));

        var blobMock = new Mock<CloudBlockBlob>(new Uri("http://tempuri.org/blob"));
        blobMock
            .Setup(m => m.ExistsAsync())
            .ReturnsAsync(true);
        _iblobprovider = new BlobServiceProvider(mockCloudBlobContainer.Object, blobMock.Object);


    }

下面是测试方法

    [Fact]
    public void DownloadFromBlob_Success()
    {
        string containerName = "d";
        string fileName = "w";
        string downloadPath = "e";
        _iblobprovider.DownloadFromBlob(containerName,fileName,downloadPath);
    }

BlobServiceProvider 类具有以下代码

 public readonly CloudBlobClient blobClient = null;
 private readonly IBlobOperations _blobOperations;
 public   CloudBlockBlob _blockBlob = null;

 public BlobServiceProvider(IBlobOperations blobOperations,CloudBlockBlob  cloudBlockBlob )
        {
            string storageConnectionString="";
            this._blobOperations = blobOperations;
              this._blockBlob= cloudBlockBlob; // this._blockBlob contains ExistsAsync() mock data which was created in TestBlobServiceProvider constructor.How can I return mock data if ExistsAsync() called.
            CloudStorageAccount storageAccount = this._blobOperations.parseConnString(storageConnectionString);
            blobClient = storageAccount.CreateCloudBlobClient();
        }

      public void DownloadFromBlob(string containerName, string fileName, string downloadPath)
        {
            CloudBlockBlob file = GetBlockBlobContainer(containerName).GetBlockBlobReference(fileName);
            var val = ReturnFileValue(file); 
            if (!val)
                throw new FileNotFoundException($"{Messages.ExMethodName} {MethodBase.GetCurrentMethod()} {Messages.ExMessage} {Messages.FileNotFound}");

            file.DownloadToFileAsync(Path.Combine(downloadPath, fileName), FileMode.Create);
        }

      private bool ReturnFileValue(CloudBlockBlob file)
        {
            var value = file.ExistsAsync(); // here I need to return mock data, but I'm not getting how can I use this._blockBlob here

            return value.Result;
        }

我知道如果我在ReturnFileValue()中使用以下内容,那么它将返回模拟数据。但是我不能在下面使用,因为我正在根据CloudBlockBlob的Input ReturnFileValue()值检查文件是否存在。

var value = this._blockBlob.ExistsAsync()

因此,如何使var value = file.ExistsAsync();返回模拟数据。

添加了截图以供参考。

enter image description here enter image description here enter image description here

0 个答案:

没有答案