【问题标题】:UnitTesting static Class (Theoretical Question)单元测试静态类(理论题)
【发布时间】:2011-11-11 10:17:08
【问题描述】:

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

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

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

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

【问题讨论】:

  • 这正是避免使用静态/单例类的原因;它排除了一些需要提供模拟实现的单元测试用例。
  • 如果您的静态类中有依赖项需要模拟以进行测试,您是否绝对确定静态类是合适的实现?

标签: c# unit-testing asp.net-mvc-3 static-classes


【解决方案1】:

我所做的是将现有的静态类用作接缝,并在不同的命名空间中提供替代实现。这意味着您可以通过尽可能少的更改来测试代码——只需更改名称空间。通常我必须这样做才能获得 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
    ...
}

我最近写了一篇博客,详细介绍了here

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-06
    • 2016-09-07
    • 2019-05-11
    • 1970-01-01
    • 2011-08-03
    • 2011-08-23
    • 1970-01-01
    相关资源
    最近更新 更多