Search code examples
unit-testingninjectfluent-assertionscompositionroot

How to test whether my factories are properly bound?


Using Ninject, I have the following and wish to test using FluentAssertions:

[Test]
public void InterfacesEndingWithFactoryShouldBeBoundAsFactories() {
    // Given
    IKernel kernel = new StandardKernel();
    kernel.Bind(services => services
        .From(AppDomain.CurrentDomain
            .GetAssemblies()
            .Where(a => !a.FullName.Contains("Tests")))
        .SelectAllInterfaces()
        .EndingWith("Factory")
        .BindToFactory()
    );

    // When
    var factory = kernel.Get<ICustomerManagementPresenterFactory>();

    // Then
    factory.Should().NotBeNull();
}

Is there any good ways to test whether the factories are actually bound properly?


Solution

  • I wrote an extension package for Fluent Assertions to test my Ninject bindings. Using it your test could be rewritten like this:

    [Test]
    public void InterfacesEndingWithFactoryShouldBeBoundAsFactories() {
        // Given
        IKernel kernel = new StandardKernel();
        kernel.Bind(services => services
            .From(AppDomain.CurrentDomain
                .GetAssemblies()
                .Where(a => !a.FullName.Contains("Tests")))
            .SelectAllInterfaces()
            .EndingWith("Factory")
            .BindToFactory()
        );
    
        // When
    
    
        // Then
        kernel.Should().Resolve<ICustomerManagementPresenterFactory>().WithSingleInstance()
    }
    

    As suggested by @Will Marcouiller, I would also extract the code to bootstrap the kernel into it's own class so it can be invoked in your app's composition root and in your unit tests.