AutoMoq is a nice little package I came across today. The AutoMoq home page describes it as follows:
AutoMoq is an "auto-mocking" container that creates objects for you. Just tell it what class to create and it will create it.
Why is this useful? Consider the following scenario. We have a BananaCakeFactory class, that relies on a Banana Repository. Here is the constructor:
public BananaCakeFactory(IBananaRepo bananaRepo);
If we want to run Unit Tests on methods in BananaCakeFactory, we will have to write all the mocking code to mock IBananaRepo. That’s fine.
Time goes on, our app grows more complex. Now our BananaCakeFactory needs to Sugar Repo as well…
public BananaCakeFactory(IBananaRepo bananaRepo, ISugarRepo sugarRepo);
We add mocks for our Sugar Repo, and update all our constructor calls for BananaCakeFactory. When we have a large solution, time spent adding new mocks and updating constructors really adds up. AutoMoq can take the pain away.
Here is an example of how we use AutoMoq to create a mocked class, ready for testing:
// init mocker = new AutoMoqer(); // mock a Banana Cake Factory var cakeFac = mocker.Create<BananaCakeFactory>(); // inject our IRepo mocker.GetMock<IBananaRepo>(); // do work var result = cakeFac.Bake();
Now if we want to add our Sugar Repo, all that’s needed is the following additional line: