Vac*_*ano 9 c# static unit-testing mocking
所以我有一个看起来像这样的课程:
public class MyClassToTest()
{
MyStaticClass.DoSomethingThatIsBadForUnitTesting();
}
Run Code Online (Sandbox Code Playgroud)
和一个看起来像这样的静态类:
public static class MyStaticClass()
{
public static void DoSomethingThatIsBadForUnitTesting()
{
// Hit a database
// call services
// write to a file
// Other things bad for unit testing
}
}
Run Code Online (Sandbox Code Playgroud)
(显然这是一个愚蠢的例子)
所以,我知道第二类在单元测试方面注定要失败,但有没有办法解开MyClassToTest类,以便我可以测试它(没有实例化MyStaticClass).基本上,我希望它忽略这个电话.
注意:遗憾的是这是一个Compact Framework项目,因此不能使用Moles和Typemock Isolator等工具:(.
Mic*_*son 12
定义一个与之相同的接口,DoSomethingThatIsBadForUnitTesting例如:
public interface IAction {
public void DoSomething();
}
Run Code Online (Sandbox Code Playgroud)
(显然,在实际代码中,你会选择更好的名字.)
然后,您可以为类编写一个简单的包装器,以便在生产代码中使用:
public class Action : IAction {
public void DoSomething() {
MyStaticClass.DoSomethingThatIsBadForUnitTesting();
}
}
Run Code Online (Sandbox Code Playgroud)
在MyClassToTest,您IAction通过其构造函数传递一个实例,并在该实例上调用该方法而不是静态类.在生产代码中,您传入具体类,Action因此代码的行为与以前一样.在单元测试中,传入一个实现的模拟对象,IAction使用模拟框架或滚动自己的模拟.