对于我的单元测试,我目前正在使用 Moq 模拟我的拦截器和拦截的类,然后在 Unity 中注册拦截的实例并为接口设置默认拦截器。然后我解析实例并调用拦截的方法,并验证正在调用拦截方法。
_mockInterceptor = new Mock<ExternalInterceptor>().As<IInterceptRelay>();
_mockInterception = new Mock<TestInterception> { CallBase = true }.As<IInterceptRelay>();
Container.RegisterInstance(_mockInterception.Object as ITestInterception);
UnityContainer.Configure<Interception>().SetDefaultInterceptorFor<ITestInterception>(new InterfaceInterceptor());
var test = Container.Resolve<ITestInterception>();
var returnValue = test.TestTheExternalInterception(TestMessage);
_mockInterceptor.Verify(i => i.ExecuteAfter(It.IsAny<object>(), It.IsAny<IEnumerable>(), It.IsAny<LoggingInterceptionAttribute>(), It.IsAny<IMethodResult>()), Times.Once());
这很好用,但是我宁愿在注册期间设置拦截,就像我在注册服务/单例时一样,以保持一切一致。
// Typical registration
UnityContainer.RegisterType<TFrom, TTo>(new Interceptor<InterfaceInterceptor>(), new InterceptionBehavior<PolicyInjectionBehavior>());
// Singleton registration
UnityContainer.RegisterType<TFrom, TTo>(new ContainerControlledLifetimeManager(), new Interceptor<InterfaceInterceptor>(), new InterceptionBehavior<PolicyInjectionBehavior>());
我看不到任何使用该方法配置拦截的IUnityContainer.RegisterInstance()
方法,因为它不需要任何InjectionMembers
. 如果我UnityContainer.Configure<Interception>().SetDefaultInterceptorFor<T>()
在解析之前调用,我实际上可以对实例使用拦截。
是否有更好/更简单的方法来注册或模拟拦截器?