Mocking is nice, automocking is even better. How can I make my NUnit BDD specs automocked?

My favorite framework for testing is Machine.Specifications in combination with Machine.Fakes for automocking support.

At work, we use:

Okay, so let’s create a base class that works with those conditions…

For inspiration, let’s look at the Machine.Fakes WithSubject base class:

  • The test fixture will inherit from WithSubject<TSubject>

Each interface or abstract base class dependency in the constructor of the type will be filled automatically by the configured fake framework. Dependency Injection with fakes so to speak.

  • Use the Subject property to access the class under test

The actual subject is created on the first read access to this property.

  • Use The<TFake>() method to access to the injected dependency

Machine.Fakes adds an abstraction over several mock frameworks. I’m only interested in one, Moq.

So my solution will use:

Example code

You can get the example code at https://github.com/hlaueriksson/ConductOfCode

WithSubject:

The With<TFake>() methods can be used to inject real or fake objects to the subject.

The subject:

The tests:

The unit test sessions:

Unit Test Sessions