The main reason for creating this package is to make writing sociable unit tests easier which is often used in the Chicago style of TDD as oppose to mocking which is more heavily used in the London style. These are also known as classicist vs mockist testing styles.
This package can also be used as a tool to help write integration tests. Please read the link above about sociable unit tests to understand the difference between the two.
Note: This package only works with the Autofac container.
When using dependency injection writing a sociable unit test often ends up with something like this:
public UnitShould() {
//common test setup
sut = new Sut(
new DependencyA(new DependencyB(), new DependencyC()),
new DependencyD(),
new DependencyE(new DependencyF())
);
}
whereas with test doubles it would look similar to:
public UnitShould() {
//common test setup
var mockA = new Mock<DependencyA>();
var mockD = new Mock<DependencyD>();
var mockE = new Mock<DependencyE>();
sut = new Sut(mockA, mockD, mockE);
}
Mocking means you only have to worry about the immediate set of dependencies rather than all of the layers.
This package can be installed via Nuget: https://www.nuget.org/packages/SociableTesting.Autofac/
With this package sociable unit tests can be setup without having to worry about initialising any of the dependencies. Instead, dependencies are initialised with the container just like they are in production. The examples below are for use with XUnit.
public class SociableTestShould
{
[Fact]
public void InitialiseRegisteredClass()
{
var setup = new SociableTest<Sut>(new MyModule());
setup.Sut.Should().BeOfType<Sut>();
}
}
It is not necessary to register all the modules in your application, if any registrations are missing when the container is built then a default mock will be used.
You can register further modules by calling setup.ProvideModule(new OtherModule());
Dependencies can be replaced in the container by using the ProvideDependency
method. ProvideDependency
must be used before any access to either the Sut
or ContainerBuilder
properties. Once either of these properties
is accessed the container is built and ProvideDependency
will no longer have any effect.
This is useful for setting up your own test doubles or fakes rather than relying on the default mocks provided.
public class SociableTestShould
{
[Fact]
public void InitialiseRegisteredClass()
{
var setup = new SociableTest<Class1>(new MyModule());
var mock = new Mock<IMockedDependency>();
ProvideDependency<IMockedDependency>(mock.Object);
setup.Sut.Should().BeOfType<Class1>();
}
}
The ContainerBuilder
is accessible via a public property on SociableTest
so you can make use of the full range of registration types Autofac provides.
setup.Container
can be used to access IContainer
directly to resolve instances in tests, such as accessing dependencies of the class under test.