简体   繁体   English

如何在ASP.NET MVC中单元测试专用控制器方法?

[英]How do I unit test private controller methods in ASP.NET MVC?

What is the best practice to unit-test private methods inside a controller in ASP.NET MVC? 在ASP.NET MVC中的控制器内部对私有方法进行单元测试的最佳实践是什么? The Currently, if I want to unit-test a private method inside a controller I have to set it to public but when I do, that method is exposed to the web. 当前,如果我想对控制器内部的私有方法进行单元测试,则必须将其设置为public,但是当我这样做时,该方法会暴露在Web上。

Is the best way to move the method to a helper class? 将方法移到助手类的最好方法是吗?

You should be moving the method into a helper class that you extracted an interface to. 您应该将方法移到提取接口的帮助器类中。 That way it's easier to perform dependency injection and switch the underlaying implementation or mock it if needed. 这样,执行依赖注入和切换底层实现或在需要时对其进行模拟就变得更加容易。
Testing private methods is a code smell (or a test smell). 测试私有方法是一种代码气味(或一种测试气味)。
Use InternalsVisibleTo trick only when you must (ie you are using an untestable class and must raise an event that is hidden from you by a protected function call). 仅在必要时才使用InternalsVisibleTo进行欺骗(即,您正在使用不可测试的类,并且必须引发受保护的函数调用对您隐藏的事件)。

You should use the private object, like this: 您应该使用私有对象,如下所示:

var privateObject = new PrivateObject(this.controller);
var result = (ActionResult)privateObject.Invoke("RegisterToEvent", shippingAddressID, creditCardID);  

you could set the method to internal instead of private, and then set the InternalsVisibleTo attribute to the name of your test assembly. 您可以将方法设置为内部而不是私有,然后将InternalsVisibleTo属性设置为测试程序集的名称。

In assembly info: 在组装信息中:

[assembly: InternalsVisibleTo("MyTestAssembly")]

我已经使用了PrivateObject ()方法,但我喜欢NonActionAttribute的Charlino的建议(见注释上面原来的问题),太。

You could create an action filter for test methods like this.... 您可以为这种测试方法创建一个动作过滤器。

public class TestActionFilter : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
         filterContext.HttpContext.Response.Redirect("loginurl");
         //or throw exception or some other action
    }
}

Or you could make the method only publicly accessible to another assembly. 或者,您可以使该方法仅可供另一个程序集公开访问。

[assembly: InternalsVisibleTo("TestAssembly")]

You can work around that problem by limiting tests to visible methods. 您可以通过将测试限制为可见方法来解决该问题。 Any private method will be used at least by one visible method (otherwise: it can safely be deleted). 任何私有方法都将至少由一种可见方法使用(否则,可以安全地删除它)。

So I suggest to develop tests that call the visible methods with practical values so that the private algorithms are tested. 因此,我建议开发可调用具有实际价值的可见方法的测试,以便测试私有算法。 If code is not reachable through visible methods - delete it. 如果无法通过可见方法访问代码,请删除它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM