asp.net-mvcninjectmstestwebactivator

Start WebActivator from unit test


I am trying to write integration tests. Therefore I need the start methods of WebActivator to be executed in the pre-start initialization stage of my unit tests.

I tried this

[TestClass]
public class UnitTests
{
    [ClassInitialize]
    public static void Init(TestContext c)
    {   
        WebActivator.ActivationManager.Run();
    }

But it would always give me error message:

Unable to create instance of class EL.NET.SecurityAdapter.Tests.UnitTests. Error: System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.InvalidOperationException: This method can only be called during the application's pre-start initialization stage..

with a stacktrace like this

System.Web.Compilation.BuildManager.ThrowIfPreAppStartNotRunning()
Microsoft.Web.Infrastructure.DynamicModuleHelper.DynamicModuleUtility.LegacyModuleRegistrar.RegisterModule(Type moduleType)
Microsoft.Web.Infrastructure.DynamicModuleHelper.DynamicModuleUtility.RegisterModule(Type moduleType)
<myproject>.Tests.App_Start.NinjectWebCommon.Start() in <myprojectPath>Tests\App_Start\NinjectWebCommon.cs: line 25
System.RuntimeMethodHandle._InvokeMethodFast(IRuntimeMethodInfo method, Object target, Object[] arguments, SignatureStruct& sig, MethodAttributes methodAttributes, RuntimeType typeOwner)
System.RuntimeMethodHandle.InvokeMethodFast(IRuntimeMethodInfo method, Object target, Object[] arguments, Signature sig, MethodAttributes methodAttributes, RuntimeType typeOwner)
System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, Boolean skipVisibilityChecks)
System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
WebActivator.BaseActivationMethodAttribute.InvokeMethod()
WebActivator.ActivationManager.RunActivationMethods[T]()
WebActivator.ActivationManager.Run()
<myproject>.Tests.UnitTests..ctor() in <myprojectPath>Tests\UnitTests.cs: line 40

I know that unit tests should work with mocks, but I really need those integration testing.


Solution

  • I wanted to run the WebActivator to create my Ninject mappings.

    I ended up creating a wrapper interface for the DI container. My repositories access the DI only via this wrapper.

    In the web application I use a Ninject-specific implementation of this interface, and for the tests I have made a custom implementation.

    I still think that it should be possible to make Ninject work in unit tests somehow, but for now this also works.