views:

98

answers:

1

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 : 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: 

Make the method virtual.

Krzysztof Koźmic
+1 I love the way you solve the problem. :)
ktutnik