如何在 ASP.NET MVC 中对私有控制器方法进行单元测试?
在 ASP.NET MVC 控制器内对私有方法进行单元测试的最佳实践是什么?目前,如果我想对控制器内的私有方法进行单元测试,我必须将其设置为公共,但是当我这样做时,该方法会暴露在网络上。
将方法移至辅助类的最佳方法是?
What is the best practice to unit-test private methods inside a controller in 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.
Is the best way to move the method to a helper class?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
您应该将该方法移至您提取接口的辅助类中。这样,可以更轻松地执行依赖项注入并切换底层实现或在需要时模拟它。
测试私有方法是一种代码味道(或测试味道)。
仅在必要时才使用InternalsVisibleTo 技巧(即,您使用的是不可测试的类,并且必须引发通过受保护的函数调用对您隐藏的事件)。
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 (i.e. you are using an untestable class and must raise an event that is hidden from you by a protected function call).
您应该使用私有对象,如下所示:
You should use the private object, like this:
您可以将该方法设置为内部方法而不是私有方法,然后将InternalsVisibleTo属性设置为测试程序集的名称。
在装配信息中:
you could set the method to internal instead of private, and then set the InternalsVisibleTo attribute to the name of your test assembly.
In assembly info:
您可以为这样的测试方法创建一个操作过滤器...
或者您可以使该方法只能由另一个程序集公开访问。
You could create an action filter for test methods like this....
Or you could make the method only publicly accessible to another assembly.
您可以通过将测试限制为可见方法来解决该问题。任何私有方法都将至少被一个可见方法使用(否则:可以安全地删除它)。
因此,我建议开发调用具有实用价值的可见方法的测试,以便测试私有算法。如果代码无法通过可见方法访问 - 删除它。
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.
我使用了 PrivateObject() 方法,但我喜欢 Charlino 对 NonActionAttribute 的建议(请参阅对上面原始问题的评论)也是如此。
I have used the PrivateObject() method but I like Charlino's suggestion of NonActionAttribute (see comments to original question above), too.