从单元测试启动网络激活器



我正在尝试编写集成测试。因此,我需要在单元测试的预启动初始化阶段执行 WebActivator 的启动方法。

我试过这个

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

但它总是会给我错误消息:

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..

使用这样的堆栈跟踪

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>TestsApp_StartNinjectWebCommon.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>TestsUnitTests.cs: line 40

我知道单元测试应该与模拟一起使用,但我真的需要这些集成测试。

我想运行WebActivator来创建我的Ninject映射。

我最终为 DI 容器创建了一个包装器接口。我的存储库仅通过此包装器访问 DI。

在 Web 应用程序中,我使用此接口的特定于 Ninject 的实现,并且对于测试,我制作了一个自定义实现。

我仍然认为应该有可能以某种方式使 Ninject 在单元测试中工作,但现在这也有效。

最新更新