How to use Moq framework to unit test azure service fabrics?

[亡魂溺海] 提交于 2021-02-08 15:36:37

问题


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;
}

回答1:


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)
    {
    }
}

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);

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.

Edit: Updated sample code to use Moq properly.



来源:https://stackoverflow.com/questions/37464593/how-to-use-moq-framework-to-unit-test-azure-service-fabrics

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!