When you are testing your application, at some point will have solve two problems:
- Creating test data you will pass to your functions
- Mocking your dependencies
Creating test data with Autofixture
Every time you test a function which takes some values as parameters, you need to provide these values. You can create it manually, but it’s cumbersome when you need to populate an object with 10 properties. Here is where Autofixture comes handy. It’s a library created by Mark Seeman. It allows you to easily create test data for your unit tests.
You can create simple value types and complex objects with properties filled with data.
Another problem while testing your application is mocking your dependencies. Imagine you have an application which has some service and a repository this service depends on:
When you are writing tests for TestService, you don’t want to use real repository implementation, which, for example, talks directly to the database. You just want to check the TestService code.
The answer to this problem is to use a mocking library. There are at least few of them available: Moq, NSubstitute and FakeItEasy. They all have similar capabilities, but my favourite is the last one - FakeItEasy.
I would like to show you how to use it on a simple example with service and repository mentioned above. In the test, I would like to check if:
- InvokeTestMethod is calling TestMethod in the repository
- Service method is returning what it got from the repository
In this example, I am using both libraries. Autofixture helps me to create a test data - in this case it’s two integers: a & b. Then I am using FakeItEasy to create a fake repository, setup a call to TestMethod and check if it was called by the service.
AutoFixture + FakeItEasy
It is also possible to configure AutoFixture to fallback to FakeItEasy when an interface is requested, but I don’t find it useful and prefer to use these libraries on their own. There is a nice post by Nikos Baxevanis explaining it here.
As you can see, not only those libraries are easy to use, but also functionality they provide is very helpful. I highly encourage you to go to AutoFixture CheatSheet and FakeItEasy QuickStart pages and check all the options available in these two libraries.