使用静态类/方法依赖项测试类

所以我有一个看起来像这样的类:

public class MyClassToTest() { MyStaticClass.DoSomethingThatIsBadForUnitTesting(); } 

和一个看起来像这样的静态类:

 public static class MyStaticClass() { public static void DoSomethingThatIsBadForUnitTesting() { // Hit a database // call services // write to a file // Other things bad for unit testing } } 

(显然这是一个愚蠢的例子)

所以,我知道第二类在unit testing方面注定要失败,但有没有办法解开MyClassToTest类,以便我可以测试它(没有实例化MyStaticClass )。 基本上,我希望它忽略这个电话。

注意:遗憾的是这是一个Compact Framework项目,所以不能使用像Moles和Typemock Isolator这样的工具:(。

定义一个与DoSomethingThatIsBadForUnitTesting完全相同的接口,例如:

 public interface IAction { public void DoSomething(); } 

(显然,在实际代码中,你会选择更好的名字。)

然后,您可以为类编写一个简单的包装器,以便在生产代码中使用:

 public class Action : IAction { public void DoSomething() { MyStaticClass.DoSomethingThatIsBadForUnitTesting(); } } 

MyClassToTest ,您通过其构造函数IAction的实例,并在该实例上调用该方法而不是静态类。 在生产代码中,您传递具体类Action因此代码的行为与以前一样。 在unit testing中,传入一个实现IAction的模拟对象,使用模拟框架或滚动自己的模拟。