2010-05-10 66 views
2

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

这里是所有相关代码:

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

回答

11

使方法变为虚拟。

+5

+1我喜欢你解决问题的方式。 :) – ktutnik 2010-08-26 01:48:22

+0

它必须是虚拟的,以便代理包装它。我们的其他图层工作,因为他们有一个特定的接口,代理可以包装 – eiu165 2013-05-03 20:17:45