Wednesday, December 18, 2013

Auto-mocking with AutoMoq

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:

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

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:

Now if we want to add our Sugar Repo, all that's needed is the following additional line:

Happy Coding!

Reference URLs

  • AutoMoq Homepage
  • AutoMoq Nuget Package
  • No comments:

    Post a Comment