We want to write unit tests faster, more robust and easier to maintain
- Too often we have broken unit tests because we have refactored code.
- Introducing or removing dependencies breaks tests because of missing arguments in constructors.
- We waste time arranging and mocking dependencies instead of focusing on testing.
- 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.
Awesome article! love your work 🙂
LikeLike