Interceptor Castle n'intercepte pas une méthode sur un contrôleur MVC au cours de test unitaire

StackOverflow https://stackoverflow.com/questions/2803700

Question

J'ai une classe de test .net. Dans la méthode Initialize, je crée un conteneur windsor et faire quelques enregistrements. Dans la méthode d'essai réelle, j'appelle une méthode sur la classe de contrôleur, mais l'intercepteur ne fonctionne pas et la méthode est appelée directement. Quelles sont les raisons possibles pour cela?

Voici tout le code correspondant:

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();
    }
}
Était-ce utile?

La solution

Faire la méthode virtuelle.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top