我正在开发一个棕地应用程序,目前正在重构其中的一部分。我正在尝试以 TDD 方式执行此操作,但遇到了问题。我正在测试的部分代码
var siteLanguages = from sl in SiteSettings.GetEnabledSiteLanguages() select sl.LanguageID;
在 GetEnabledLanguages
具有以下签名的
public static List<LanguageBranch> GetEnabledSiteLanguages();
情况下依次调用数据访问代码来检索相关信息。到目前为止,我已经使用接口和 DI 在单元测试期间对此类依赖项使用不同的存根实现。但由于 GetEnabledSiteLanguages
方法是静态的,因此这不起作用。在这种情况下,“正确”的做法是什么?
I am working on a brownfield application and am currently refactoring part of it. I am trying to do this in a TDD fashion but am running into a problem. Part of the code I am testing does
var siteLanguages = from sl in SiteSettings.GetEnabledSiteLanguages() select sl.LanguageID;
where GetEnabledLanguages
has the following signature
public static List<LanguageBranch> GetEnabledSiteLanguages();
it in turns calls data access code to retrieve the relevant information. Up untill now I have used a interface and DI to use a different stub implementation for these kind of dependencies during unit testing. But since the GetEnabledSiteLanguages
method is static this will not work. What is the "correct" way to do it in this case?
发布评论
评论(4)
您可以创建一个实现接口的对象,并将其实现注入到使用
SiteSettings
类的类中。该接口声明的方法与您需要拦截的静态方法具有相同的签名。然后,您可以模拟测试接口并创建一个委托给实际代码的静态方法的实现:...在依赖类中:
you could create a object which implements an interface and inject an implementation of this into the class which uses the
SiteSettings
class. The interface declare the method with the same signature as the static method(s) you need to intercept. Then you could mock out the interface for tests and create a single implementation which delegates to the static method for the actual code:... in the dependent class:
怎么样让你的方法像这样:
现在它成为第一类对象(作为 Func 委托)并且存根可以替换它
What about making your method such as:
Now it becomes first class object (as Func delegate) and a stub can replace it
查看
Moles
框架。Look at
Moles
framework.您可以使用 JustMock、TypeMock 或 moles。这些工具允许您模拟一切,例如静态方法。
You can use tools like JustMock, TypeMock or moles. These tools allow you to mock everythings like static methods.