简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM