开发者

Castle interceptor does not intercept a method on an MVC Controller during unit test

开发者 https://www.devze.com 2022-12-29 23:56 出处:网络
I have a .net test class. In the Initialize method, I create a windsor container and make some registrations. In the actual test method, I call a method on the controller class but the interceptor doe

I have a .net test class. In the Initialize method, I create a windsor container and make some registrations. In the actual test method, I call a method on the controller class but the interceptor does not work and the method gets directly called. What are potential reasons for this?

Here is all the related code:

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 : IInterceptorSelect开发者_如何转开发or
{
    public IInterceptor[] SelectInterceptors(Type type, MethodInfo method, IInterceptor[] interceptors)
    {
        return 
            method.ReturnType == typeof(JsonResult) 
            ? interceptors 
            : interceptors.Where(x =>  !(x is SomeInterceptor)).ToArray();
    }
}


Make the method virtual.

0

精彩评论

暂无评论...
验证码 换一张
取 消