1

對於我的單元測試,我目前使用Moq來嘲笑我的攔截器和攔截類,然後在Unity中註冊截獲的實例並設置接口的默認攔截器。然後我解析實例並調用截獲的方法,並驗證攔截方法正在被調用。用於在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>(),我實際上可以使用攔截。

是否有更好/更簡單的方式註冊或嘲笑攔截器?

+0

什麼是你試圖在這裏測試?你不需要任何模擬,因爲你的單元測試不需要測試Unity可以執行截取。我甚至會爭辯說,你不應該在你的單元測試中使用Unity(只是將你正在測試的課程新增)。使用反射來確定LoggingInterception屬性是否出現在被測試的成員上同樣有效。 – TylerOhlsen 2014-10-06 19:57:04

+0

@TylerOhlsen在典型的情況下,這是真的,但是我使用抽象的IoC框架,它允許任何IoC容器在Unity中被放置。在這些情況下,我針對支持截取的所有IoC框架運行相同的測試,並測試抽象如預期的那樣工作。 – 2014-10-06 21:57:19

回答

5

Unity Interception提供了創建代理而不用統一解決它們的問題。然後你可以自己創建的對象RegisterInstance

欲瞭解更多信息,請參閱Dependency Injection with Unity第77頁「沒有統一容器的攔截」。

我從here下面的例子:

ITenantStore tenantStore = Intercept.ThroughProxy<ITenantStore>(
    new TenantStore(tenantContainer, blobContainer), 
    new InterfaceInterceptor(), 
    new IInterceptionBehavior[] 
    { 
     new LoggingInterceptionBehavior(), 
     new CachingInterceptionBehavior() 
    }); 
+0

謝謝,這會做得很好。 – 2014-10-07 11:30:01

+0

如果該對象在您到達此處時已創建,該怎麼辦? – claudekennilol 2017-07-14 19:18:09

+0

@claudekennilol哪個對象? TenantStore?只需將新的TenantStore(tenantContainer,blobContainer)替換爲對現有對象的引用即可...... – BatteryBackupUnit 2017-07-15 11:27:39