测试具有静态类/方法依赖关系的类 [英] Testing a Class with a Static Class/method dependency

查看:59
本文介绍了测试具有静态类/方法依赖关系的类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

So I have a class that looks like this:

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

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

and a static class that looks like this:

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

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

(Obviously this is a dumbed down example)

因此,我知道第二类在单元测试中注定要失败,但是有什么方法可以取消MyClassToTest类的耦合,以便我可以对其进行测试(而无需实例化MyStaticClass).基本上,我希望它忽略此调用.

So, I know that the second class is doomed when it comes to unit testing, but is there any way to uncouple the MyClassToTest class so that I can test it (WITHOUT instantiating MyStaticClass). Basically, I would want it to ignore this call.

注意:遗憾的是,这是一个紧凑框架项目,因此无法使用Moles和Typemock Isolator之类的工具:(.

Note: Sadly this is a Compact Framework Project, so tools like Moles and Typemock Isolator cannot be used :(.

推荐答案

定义与DoSomethingThatIsBadForUnitTesting具有相同功能的接口,例如:

Define an interface that does the same thing as DoSomethingThatIsBadForUnitTesting, for instance:

public interface IAction {
    public void DoSomething();
}

(显然,在真实代码中,您会选择更好的名称.)

(Obviously, in real code, you'd pick better names.)

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

Then you can write a simple wrapper for the class for use in production code:

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

MyClassToTest中,通过其构造函数传入IAction的实例,然后在该实例上调用方法,而不是调用静态类.在生产代码中,您传递了具体的类Action,因此该代码的行为与以前相同.在单元测试中,您使用模拟框架或滚动自己的模拟来传递实现IAction的模拟对象.

In MyClassToTest, you pass in an instance of IAction via its constructor and call the method on that instance instead of the static class. In production code, you pass in the concrete class Action so the code behaves as before. In the unit test, you pass in a mock object that implements IAction, either using a mock framework or rolling your own mock.

这篇关于测试具有静态类/方法依赖关系的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆