我已经重写了 Controller 的 OnActionExecuting 方法,以根据正在执行的 filterContext 设置一些内部状态。我该如何测试这个?该方法本身是 protected ,所以我假设我必须在调用堆栈中更高。
我需要什么代码来测试这个?
我正在使用 mvc RC 1。
编辑:我也在使用 nunit。
谢谢
最佳答案
您需要添加和使用 Private Accessor。右键单击您的 Controller 类并选择 Create Private Accessors
从菜单中将它们添加到您的测试项目中。进入测试项目后,创建 Controller ,然后为其创建访问器。该方法应该在访问器上可用。这是我自己的代码中的示例测试:
/// <summary>
///A test for OnActionExecuting
///</summary>
[TestMethod()]
[ExpectedException( typeof( InvalidOperationException ) )]
public void OnActionExecutingWindowsIdentityTest()
{
var identity = WindowsIdentity.GetCurrent();
WindowsPrincipal principal = new WindowsPrincipal( identity );
var httpContext = MockRepository.GenerateStub<HttpContextBase>();
httpContext.User = principal;
var actionDescriptor = MockRepository.GenerateStub<ActionDescriptor>();
RouteData routeData = new RouteData();
BaseController controller = new BaseController();
BaseController_Accessor accessor = new BaseController_Accessor( new PrivateObject( controller ) );
ControllerContext controllerContext = MockRepository.GenerateStub<ControllerContext>( httpContext, routeData, controller );
ActionExecutingContext filterContext = new ActionExecutingContext( controllerContext, actionDescriptor, new Dictionary<string, object>() );
accessor.OnActionExecuting( filterContext );
}
编辑 :如果您没有使用 MSTest 进行单元测试,则可能必须手动生成访问器。本质上,您创建一个包装器类,通过等效的公共(public)方法公开被测类的私有(private)/ protected 方法,将被测类的实例传递给包装器,然后使用包装器类的反射来调用私有(private)/ protected 方法被测类的方法。
public class MyClass
{
protected void DoSomething( int num )
{
}
}
public class MyClass_accessor
{
private MyClass privateObj;
public MyClass_accessor( MyClass obj )
{
this.privateObj = obj;
}
public void DoSomething( int num )
{
MethodInfo info = privateObj.GetType()
.GetMethod("DoSomething",
BindingFlags.NonPublic
| BindingFlags.Instance );
info.Invoke(obj,new object[] { num });
}
}
关于asp.net-mvc - 如何对我的 asp.net-mvc Controller 的 OnActionExecuting 方法进行单元测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/591720/