所以我正在尝试测试Azure表存储并模拟我所依赖的东西。我的类的结构方式是在构造函数中建立连接,即我创建一个新的CloudStorageAccount
实例,在其中创建一个具有storageName
和storageKey
的StorageCredentials
实例。然后,我创建了一个CloudTable
的实例,在代码中进一步使用它来执行CRUD操作。我的课程如下:
public class AzureTableStorageService : ITableStorage
{
private const string _records = "myTable";
private CloudStorageAccount _storageAccount;
private CloudTable _table;
public AzureTableStorageService()
{
_storageAccount = new CloudStorageAccount(new StorageCredentials(
ConfigurationManager.azureTableStorageName, ConfigurationManager.azureTableStorageKey), true);
_table = _storageAccount.CreateCloudTableClient().GetTableReference(_records);
_table.CreateIfNotExistsAsync();
}
//...
//Other methods here
}
_table
在整个类中被重复使用,用于不同的目的。我的目标是模拟它,但由于它是虚拟的,没有实现任何接口,我无法想出一个简单的Mock
解决方案,比如:
_storageAccount = new Mock<CloudStorageAccount>(new Mock<StorageCredentials>(("dummy", "dummy"), true));
_table = new Mock<CloudTable>(_storageAccount.Object.CreateCloudTableClient().GetTableReference(_records));
因此,当我尝试以这种方式构建我的单元测试时,我得到了:Type to mock must be an interface or an abstract or non-sealed class.
我的目标是完成这样的事情:
_table.Setup(x => x.DoSomething()).ReturnsAsync("My desired result");
任何想法都将不胜感激!
我也在努力实现与Azure表存储绑定的Azure函数的单元测试。我最终使用了一个派生的CloudTable类,在那里我可以覆盖我使用的方法并返回固定的结果。
/// <summary>
/// Mock class for CloudTable object
/// </summary>
public class MockCloudTable : CloudTable
{
public MockCloudTable(Uri tableAddress) : base(tableAddress)
{ }
public MockCloudTable(StorageUri tableAddress, StorageCredentials credentials) : base(tableAddress, credentials)
{ }
public MockCloudTable(Uri tableAbsoluteUri, StorageCredentials credentials) : base(tableAbsoluteUri, credentials)
{ }
public async override Task<TableResult> ExecuteAsync(TableOperation operation)
{
return await Task.FromResult(new TableResult
{
Result = new ScreenSettingEntity() { Settings = "" },
HttpStatusCode = 200
});
}
}
我通过传递存储模拟器用于本地存储的配置字符串来实例化mock类(请参阅https://learn.microsoft.com/en-us/azure/storage/common/storage-configure-connection-string)。
var mockTable = new MockCloudTable(new Uri("http://127.0.0.1:10002/devstoreaccount1/screenSettings"));
在本例中,"screenSettings"是表的名称。
模拟类现在可以从单元测试中传递给Azure函数。
也许这就是你想要的?
在这里添加答案,因为您的目标是使用模拟框架,只需设置一个从CloudTable继承并提供默认构造函数的对象,就可以模拟继承的对象本身并控制它返回的内容:
public class CloudTableMock : CloudTable
{
public CloudTableMock() : base(new Uri("http://127.0.0.1:10002/devstoreaccount1/screenSettings"))
{
}
}
那么这只是一个创建mock的例子。我正在使用NSubstitute,所以我使用了:
_mockTable = Substitute.For<CloudTableMock>();
但我的猜测是国防部会允许:
_mockTableRef = new Mock<CloudTable>();
_mockTableRef.Setup(x => x.DoSomething()).ReturnsAsync("My desired result");
_mockTable = _mockTableRef.Object;
(我的Moq有点生疏,所以我猜上面的语法不太正确(
我遇到了与所选答案相同的场景,涉及具有表绑定的Azure函数。使用模拟CloudTable
有一些限制,特别是当将System.Linq
与CreateQuery<T>
一起使用时,例如,因为这些是IQueryable
上的扩展方法。
更好的方法是将HttpMessageHandler
mock(如RichardSzalay.MockHttp(与TableClientConfiguration.RestExecutorConfiguration.DelegatingHandler
一起使用,然后从表中剔除您期望的json响应。
public class Azure_Function_Test_With_Table_Binding
{
[Fact]
public void Should_be_able_to_stub_out_a_CloudTable()
{
var storageAccount = StorageAccount.NewFromConnectionString("UseDevelopmentStorage=true");
var client = storageAccount.CreateCloudTableClient();
var mockedRequest = new MockHttpMessageHandler()
.When("http://127.0.0.1:10002/devstoreaccount1/pizzas*")
.Respond("application/json",
@"{
""value"": [
{
""Name"": ""Pepperoni"",
""Price"": 9.99
}
]
}");
client.TableClientConfiguration.RestExecutorConfiguration.DelegatingHandler = new MockedRequestAdapter(mockedRequest);
var table = client.GetTableReference("pizzas");
var request = new DefaultHttpContext().Request;
request.Query = new QueryCollection(new Dictionary<string, StringValues> { { "Pizza", new StringValues("Pepperoni") } });
var result = PizzaStore.Run(request, table, null);
Assert.IsType<OkObjectResult>(result);
}
}
public class MockedRequestAdapter : DelegatingHandler
{
private readonly MockedRequest _mockedRequest;
public MockedRequestAdapter(MockedRequest mockedRequest) : base()
{
_mockedRequest = mockedRequest;
}
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
return await _mockedRequest.SendAsync(new HttpRequestMessage(request.Method, request.RequestUri), cancellationToken);
}
}
public static class PizzaStore
{
[FunctionName("PizzaStore")]
public static IActionResult Run(
[HttpTrigger(AuthorizationLevel.Function, "get", Route = null)] HttpRequest req,
[Table("pizzas", Connection = "AzureWebJobsStorage")] CloudTable cloud,
ILogger log)
{
if (req.Query.TryGetValue("Pizza", out var value))
{
var pizza = cloud.CreateQuery<Pizza>().Where(p => p.Name == value.ToString()).SingleOrDefault();
return new OkObjectResult(new { Pizza = pizza.Name, Price = pizza.Price });
}
return new NotFoundResult();
}
}
public class Pizza : TableEntity
{
public string Name { get; set; }
public double Price { get; set; }
}
下面是我的实现:
public class StorageServiceTest
{
IStorageService _storageService;
Mock<CloudStorageAccount> _storageAccount;
[SetUp]
public void Setup()
{
var c = new StorageCredentials("dummyStorageAccountName","DummyKey");
_storageAccount = new Mock<CloudStorageAccount>(c, true);
_storageService = new StorageService(_storageAccount.Object);
}
[Test]
[TestCase("ax0-1s", "random-1")]
public void get_content_unauthorized(string containerName,string blobName)
{
//Arrange
string expectOutputText = "Something on the expected blob";
Uri uri = new Uri("https://somethig.com//");
var blobClientMock = new Mock<CloudBlobClient>(uri);
_storageAccount.Setup(a => a.CreateCloudBlobClient()).Returns(blobClientMock.Object);
var cloudBlobContainerMock = new Mock<CloudBlobContainer>(uri);
blobClientMock.Setup(a => a.GetContainerReference(containerName)).Returns(cloudBlobContainerMock.Object);
var cloudBlockBlobMock = new Mock<CloudBlockBlob>(uri);
cloudBlobContainerMock.Setup(a => a.GetBlockBlobReference(blobName)).Returns(cloudBlockBlobMock.Object);
cloudBlockBlobMock.Setup(a => a.DownloadTextAsync()).Returns(Task.FromResult(expectOutputText));
//Act
var actual = _storageService.DownloadBlobAsString(containerName, blobName);
//Assert
Assert.IsNotNull(actual);
Assert.IsFalse(string.IsNullOrWhiteSpace(actual.Result));
Assert.AreEqual(actual.Result, expectOutputText);
}
}
服务类实现:
Task<string> IStorageService.DownloadBlobAsString(string containerName, string blobName)
{
var blobClient = this.StorageAccountClient.CreateCloudBlobClient();
var blobContainer = blobClient.GetContainerReference(containerName);
var blobReference = blobContainer.GetBlockBlobReference(blobName);
var blobContentAsString = blobReference.DownloadTextAsync();
return blobContentAsString;
}
假设您使用的是Microsoft.WindowsAzure.Storage
命名空间中的类,使用NSubstitute创建mock相对容易,例如:
var mockStorageAccount = Substitute.For<CloudStorageAccount>(
CloudStorageAccount.DevelopmentStorageAccount.Credentials,
false);
var mockQueueClient = Substitute.For<CloudQueueClient>(
mockStorageAccount.QueueStorageUri,
mockStorageAccount.Credentials);
等等。