我有一个 .net 测试课程。在 Initialize 方法中,我创建了一个 Windsor 容器并进行了一些注册。在实际的测试方法中,我在控制器类上调用了一个方法,但是拦截器不起作用,直接调用了该方法。造成这种情况的潜在原因是什么?
以下是所有相关代码:
测试.cs:
private SomeController _someController;
[TestInitialize]
public void Initialize()
{
Container.Register(Component.For<SomeInterceptor>());
Container.Register(
Component.For<SomeController>()
.ImplementedBy<SomeController>()
.Interceptors(InterceptorReference.ForType<SomeInterceptor>())
.SelectedWith(new DefaultInterceptorSelector())
.Anywhere);
_someController = Container.Resolve<SomeController>();
}
[TestMethod]
public void Should_Do_Something()
{
_someController.SomeMethod(new SomeParameter());
}
SomeController.cs:
[HttpPost]
public JsonResult SomeMethod(SomeParameter parameter)
{
throw new Exception("Hello");
}
SomeInterceptor.cs:
public class SomeInterceptor : IInterceptor
{
public void Intercept(IInvocation invocation)
{
// This does not gets called in test but gets called in production
try
{
invocation.Proceed();
}
catch
{
invocation.ReturnValue = new SomeClass();
}
}
}
DefaultInterceptorSelector.cs:
public class DefaultInterceptorSelector : IInterceptorSelector
{
public IInterceptor[] SelectInterceptors(Type type, MethodInfo method, IInterceptor[] interceptors)
{
return
method.ReturnType == typeof(JsonResult)
? interceptors
: interceptors.Where(x => !(x is SomeInterceptor)).ToArray();
}
}