Supercharging your unit tests

We want to write unit tests faster, more robust and easier to maintain

  1. Too often we have broken unit tests because we have refactored  code.
  2. Introducing or removing dependencies breaks tests because of missing arguments in constructors.
  3. We waste time arranging and mocking dependencies instead of focusing on testing.
  4. Repetitive plumbing code to mock and inject dependencies.

Auto-mocking Containers to the rescue

A blog by Mark Seemann explains how to use dependency injection and an auto-mocking framework to buff up those fragile tests.

How it works

  • Leverages dependency injection to construct and inject dependencies to decouple your tests from implementation details.
  • Leverages auto-mocking frameworks to mock out dependencies to reduce boilerplate code when arranging tests.

Auto-Fixture for .NET leverages IoC with your choice of mocking framework to reduce plumbing code when arranging tests.

  • Support for NUnit and XUnit
  • A choice of mocking frameworks – Moq, NSubstitute, RhinoMock and FakeItEasy
  • Test data generation

Examples

Before

[Fact]
public void TestForSomething()
{
    // Arrange
    var dependencyA = Mock.For<IDependencyA>();
    var dependencyB = Mock.For<IDependencyB>();
    var service = new Service(dependencyA, dependencyB);
    // ...
}

After

[Fact]
public void TestForSomething()
{
    // Arrange
    var fixture = new Fixture().Customize(new AutoMoqCustomization())
    var service = fixture.Create<Service>();
    // ...
}

Now if you ever refactor your service to have more dependencies, your existing tests will continue to build and pass.

2 thoughts on “Supercharging your unit tests”

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s