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;
}
The Moq framework is an open source unit testing framework that works very well with . NET code and Phil shows us how to use it.
It is used in unit testing to isolate your class under test from its dependencies and ensure that the proper methods on the dependent objects are being called.
The advantages of using Moq is, we can unit test the code successfully without using an external dependency object in the test code. Conclusion: NUnit and Moq are the suitable frameworks for testing the MVC Model layer.
Moq, how it works The idea is to create a concrete implementation of an interface and control how certain methods on that interface responds when called. This will allow us to essentially test all of the paths through code.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With