0

我知道什么时候可以使用静态类,但我的简单问题是:

如果在对包含静态类的代码进行单元测试时出现大问题?

只使用常规实例类更好吗?

谢谢(我知道有一些关于这个的问题,但所有问题都是基于特定情况的,我只想对此有一个一般性的看法)

4

1 回答 1

0

我所做的是将现有的静态类用作接缝,并在不同的命名空间中提供替代实现。这意味着您可以通过尽可能少的更改来测试代码——只需更改名称空间。通常我必须这样做才能绕过 C# 文件系统操作——File.Exists 等。

说你的方法基本上是这样做的:

using System.IO;

public void SomeMethod()
{
    ...
    if(File.Exists(myFile))
    {
        ...
    }
    ...
}

然后我会用另一种方法替换 File 的实现。替代实现应该删除任何现有方法,并在幕后调用委托实现——例如

namespace IO.Abstractions 
{     
    public static class File
    {         
        public static Func<string, string, string> ExistsImpl =
                                                      System.IO.File.Exists;

        public static string Exists(string path)
        {             
            return ExistsImpl (path);
        }
    }
} 

然后我会修改原始代码,使其使用新的命名空间:

using IO.Abstractions;

public void SomeMethod()
{
    ...
    if(File.Exists(myFile))
    {
        ...
    }
    ...
}

然后,在您的测试中,您可以只提供 File.Exists 行为的替代实现,例如:

[Test]
public void SomeTest()
{
    // arrange
    ...
    File.ExistsImpl = (path) => true; // to just default to true for every call
    ...

    // act
    someClass.SomeMethod();

    // then assert
    ...
}

我最近在这里写了一篇博客,其中包含更多详细信息。

于 2011-10-07T07:33:01.503 回答