単体テストでは、現在、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>()
解決する前に呼び出すと、実際にインスタンスで傍受を使用できます。
インターセプターを登録またはモックするより良い/簡単な方法はありますか?