c# – 如何使用Moq框架对天蓝色服务结构进行单元测试?
作者:互联网
我计划使用Moq对我的Azure服务结构应用程序进行单元测试.我在这里看到了一些例子https://github.com/Azure-Samples/service-fabric-dotnet-web-reference-app/blob/master/ReferenceApp/Inventory.UnitTests/InventoryServiceTests.cs.我看到的测试似乎实际上写的是可靠的字典而不是嘲笑.有没有办法模拟可靠字典中的添加/删除?我如何对下面的内容进行单元测试
public async Task<bool> AddItem(MyItem item)
{
var items = await StateManager.GetOrAddAsync<IReliableDictionary<int, MyItem>>("itemDict");
using (ITransaction tx = this.StateManager.CreateTransaction())
{
await items.AddAsync(tx, item.Id, item);
await tx.CommitAsync();
}
return true;
}
解决方法:
首先在服务中设置DI,以便注入模拟StateManager.您可以使用将IReliableStateManagerReplica作为参数的构造函数来执行此操作
public class MyStatefulService : StatefulService
{
public MyStatefulService(StatefulServiceContext serviceContext, IReliableStateManagerReplica reliableStateManagerReplica)
: base(serviceContext, reliableStateManagerReplica)
{
}
}
然后在测试中,当您在创建被测系统(服务)时,使用模拟IReliableStateManagerReplica
var reliableStateManagerReplica = new Mock<IReliableStateManagerReplica>();
var codePackageActivationContext = new Mock<ICodePackageActivationContext>();
var serviceContext = new StatefulServiceContext(new NodeContext("", new NodeId(8, 8), 8, "", ""), codePackageActivationContext.Object, string.Empty, new Uri("http://boo.net"), null, Guid.NewGuid(), 0L);
var myService = new MyService(serviceContext, reliableStateManagerReplica.Object);
然后设置reliableStateManagerReplica以返回模拟可靠字典.
var dictionary = new Mock<IReliableDictionary<int, MyItem>>();
reliableStateManagerReplica.Setup(m => m.GetOrAddAsync<IReliableDictionary<int, MyItem>>(name).Returns(Task.FromResult(dictionary.Object));
最后,在模拟字典中设置任何模拟行为.
编辑:更新了示例代码以正确使用Moq.
标签:c,unit-testing,moq,azure,azure-service-fabric 来源: https://codeday.me/bug/20190527/1166718.html