[英]Unit testing non-public methods in dotnet core controller
Suppose in an MVC5 controller I had a method in my controller that gets called by other methods in the controller, but I don't want it available to a user. 假设在MVC5控制器中,我的控制器中有一个方法被控制器中的其他方法调用,但是我不希望该方法可供用户使用。 If I wanted to be able to mock it, it would look like this: 如果我想能够模拟它,它将看起来像这样:
[ChildActionOnly]
public virtual string DoSpecialFormatting(string mySpecialString)
{
// stuff
}
Or I could have tossed [assembly: InternalsVisibleTo("MyLittleProject.Tests")]
and [assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")]
(for Moq) into AssemblyInfo.cs
and marked the method as internal
instead of public
: 或者,我可能已经将[assembly: InternalsVisibleTo("MyLittleProject.Tests")]
和[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")]
(对于Moq而言)扔到AssemblyInfo.cs
并将该方法标记为internal
而不是public
:
internal virtual string DoSpecialFormatting(string mySpecialString)
{
// stuff
}
Now that there is no ChildActionOnly
and I don't see an AssemblyInfo.cs
file in my new ASP.NET Core project, how would I have methods in my controller class which web users cannot access but can still be mocked? 既然现在没有ChildActionOnly
并且在新的ASP.NET Core项目中也看不到AssemblyInfo.cs
文件,那么我的控制器类中将如何有Web用户无法访问但仍然可以被模拟的方法?
You can extract that method to a class , ie named SpecialFormatter, and inject to the controller via DI. 您可以将该方法提取到一个类中,即名为SpecialFormatter,然后通过DI注入到控制器中。 To test your controller you can mock this class. 要测试您的控制器,您可以模拟此类。
class SpecialFormatter
{
public string DoSpecialFormatting(string mySpecialString)
{
// stuff
}
}
Then in your controller 然后在您的控制器中
class SomeController : Controller
{
private SpecialFormatter _formatter;
public SomeController(SpecialFormatter formatter)
{
_formatter = formatter;
}
public ActionResult SomeAction(string input)
{
string output = _formatter.DoSpecialFormatting(input);
// stuff
}
}
In ASP.NET Core the attribute is called NonActionAttribute
. 在ASP.NET Core中,该属性称为NonActionAttribute
。
[NonAction]
public virtual string DoSpecialFormatting(string mySpecialString)
{
// stuff
}
Imho its better than internal. 恕我直言,它比内部更好。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.