[英]How to use Moq framework to unit test azure service fabrics?
I am planning to use Moq for unit testing my azure service fabric application. 我计划使用Moq对我的Azure服务结构应用程序进行单元测试。 I saw some of the examples here https://github.com/Azure-Samples/service-fabric-dotnet-web-reference-app/blob/master/ReferenceApp/Inventory.UnitTests/InventoryServiceTests.cs .
我在这里看到了一些例子https://github.com/Azure-Samples/service-fabric-dotnet-web-reference-app/blob/master/ReferenceApp/Inventory.UnitTests/InventoryServiceTests.cs 。 The test I saw seems like actually writing to reliable dictionary and not mocking.
我看到的测试似乎实际上写的是可靠的字典,而不是嘲笑。 Is there way to mock the add/remove from reliable dictionary?
有没有办法模拟可靠字典中的添加/删除? How do I unit test something like below
我如何对下面的内容进行单元测试
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;
}
First set up your DI in your services so that you can inject a mock StateManager
. 首先在服务中设置DI,以便注入模拟
StateManager
。 You can do that using a constructor that takes an IReliableStateManagerReplica
as a parameter 您可以使用将
IReliableStateManagerReplica
作为参数的构造函数来执行此操作
public class MyStatefulService : StatefulService
{
public MyStatefulService(StatefulServiceContext serviceContext, IReliableStateManagerReplica reliableStateManagerReplica)
: base(serviceContext, reliableStateManagerReplica)
{
}
}
Then in your tests, when you're creating your system under test (the service), use a mock IReliableStateManagerReplica
然后在测试中,当您在创建被测系统(服务)时,使用模拟
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);
And then set up the reliableStateManagerReplica
to return a mock reliable dictionary. 然后设置
reliableStateManagerReplica
以返回模拟可靠字典。
var dictionary = new Mock<IReliableDictionary<int, MyItem>>();
reliableStateManagerReplica.Setup(m => m.GetOrAddAsync<IReliableDictionary<int, MyItem>>(name).Returns(Task.FromResult(dictionary.Object));
Finally, setup any mock behaviors on your mock dictionary. 最后,在模拟字典中设置任何模拟行为。
Edit: Updated sample code to use Moq properly. 编辑:更新了示例代码以正确使用Moq。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.