Question

I've just switched to using the NInject.MockingKernel extension for my tests (NSubstitute).

However, it makes very hard to run my Web API integration tests because it will return mocks for all Web API interfaces also.

Can I automatically limit its application only to namespaces of my own?

Was it helpful?

Solution

I don't see how that is possible out of the box. Although it's not very hard to create such a kernel on your own.

This sample is of course very minimalistic though, but it should show you how it could be done. Or maybe there is someone with more knowledge of the Ninject internals.

public class NamespaceFilteringMockMissingBindingsResolver : MockMissingBindingResolver
 {
    public NamespaceFilteringMockMissingBindingsResolver(IMockProviderCallbackProvider mockProviderCallbackProvider)
        : base(mockProviderCallbackProvider)
    {
    }

    protected override bool TypeIsInterfaceOrAbstract(Type service)
    {
        return base.TypeIsInterfaceOrAbstract(service) && service.Namespace != null && service.Namespace.StartsWith("YourNamespace");
    }
 }

public class CustomNSubstituteMockingKernel : NSubstituteMockingKernel
{
    public CustomNSubstituteMockingKernel()
    {
        this.AddComponents();
    }

    public CustomNSubstituteMockingKernel(INinjectSettings settings, params INinjectModule[] modules)
        : base(settings, modules)
    {
        this.AddComponents();
    }

    private new void AddComponents()
    {
        this.Components.RemoveAll<IMissingBindingResolver>();
        this.Components.Add<IMissingBindingResolver, SingletonSelfBindingResolver>();
        this.Components.Add<IMissingBindingResolver, NamespaceFilteringMockMissingBindingsResolver>();
    }
}

Update You are right, you don't need to create your own kernel. You can also do it like this.

var kernel = new NSubstituteMockingKernel();
kernel.Components.RemoveAll<IMissingBindingResolver>();
kernel.Components.Add<IMissingBindingResolver, SingletonSelfBindingResolver>();
kernel.Components.Add<IMissingBindingResolver, NamespaceFilteringMockMissingBindingsResolver>();

Creating your own kernel might just be more handy than always writing those extra lines. Or you create some kind of factory method.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top