如何使用Moq框架对Azure Service Fabric进行单元测试? [英] How to use Moq framework to unit test azure service fabrics?

查看:63
本文介绍了如何使用Moq框架对Azure Service Fabric进行单元测试?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我计划使用Moq来对我的Azure Service Fabric应用程序进行单元测试.我在这里看到了一些示例 https://github.com/Azure-Samples/service-fabric-dotnet-web-reference-app/blob/master/ReferenceApp/Inventory.UnitTests/InventoryServiceTests.cs .我看到的测试似乎实际上是在写可靠的字典,而不是在嘲笑.有没有办法模拟可靠字典中的添加/删除?如何对下面的内容进行单元测试

I am planning to use Moq for unit testing my azure service fabric application. 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. 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;
}

推荐答案

首先在服务中设置DI,以便可以注入模拟 StateManager .您可以使用将 IReliableStateManagerReplica 作为参数的构造函数来做到这一点

First set up your DI in your services so that you can inject a mock StateManager. You can do that using a constructor that takes an IReliableStateManagerReplica as a parameter

public class MyStatefulService : StatefulService 
{
    public MyStatefulService(StatefulServiceContext serviceContext, IReliableStateManagerReplica reliableStateManagerReplica)
        : base(serviceContext, reliableStateManagerReplica)
    {
    }
}

然后在测试中,当您创建被测系统(服务)时,请使用模拟 IReliableStateManagerReplica

Then in your tests, when you're creating your system under test (the service), use a mock 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 以返回模拟的可靠字典.

And then set up the reliableStateManagerReplica to return a mock reliable dictionary.

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.

更新了示例代码以正确使用Moq.

Updated sample code to use Moq properly.

这篇关于如何使用Moq框架对Azure Service Fabric进行单元测试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆