Lock interceptor does not intercept method on MVC controller during unit test

I have a .net test class. In the Initialize method, I create a Windsor container and do some registrations. In the actual test method, I call a method in the controller class, but the interceptor fails and the method gets called directly. What are the potential reasons for this?

Here's 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 : IInterceptorSelector
{
    public IInterceptor[] SelectInterceptors(Type type, MethodInfo method, IInterceptor[] interceptors)
    {
        return 
            method.ReturnType == typeof(JsonResult) 
            ? interceptors 
            : interceptors.Where(x =>  !(x is SomeInterceptor)).ToArray();
    }
}

      

+2


a source to share


1 answer


Make the method virtual.



+11


a source







All Articles