Ale*_*ese 1 c# unit-testing unity-container unity-interception interception
对于我的单元测试我目前正在使用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());
Run Code Online (Sandbox Code Playgroud)
这很好用,但是我宁愿在注册期间设置拦截,就像我在注册服务/单例时保持一致性一样.
// 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>());
Run Code Online (Sandbox Code Playgroud)
我看不到使用该IUnityContainer.RegisterInstance()方法配置拦截的任何方法,因为它不需要任何方法InjectionMembers.如果我UnityContainer.Configure<Interception>().SetDefaultInterceptorFor<T>()在解析之前调用,我实际上可以使用实例拦截.
是否有更好/更简单的注册或嘲笑拦截器的方法?
Unity Interception提供创建代理而无需通过统一解析它们.然后RegisterInstance,您可以自己创建对象.
有关更多信息,请参阅Unity的依赖注入第77页"没有Unity容器的拦截".
我从这里拿了下面的例子:
ITenantStore tenantStore = Intercept.ThroughProxy<ITenantStore>(
new TenantStore(tenantContainer, blobContainer),
new InterfaceInterceptor(),
new IInterceptionBehavior[]
{
new LoggingInterceptionBehavior(),
new CachingInterceptionBehavior()
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2230 次 |
| 最近记录: |