Castle拦截器在单元测试期间不拦截MVC控制器上的方法

时间:2010-05-10 15:02:39

标签: castle-windsor mstest interceptor

我有一个.net测试类。在Initialize方法中,我创建了一个windsor容器并进行了一些注册。在实际的测试方法中,我在控制器类上调用一个方法,但是拦截器不起作用,并且直接调用该方法。有什么可能的原因?

以下是所有相关代码:

test.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();
    }
}

1 个答案:

答案 0 :(得分:11)

使方法成为虚拟。