且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在单元测试静态类/方法/属性,停止与否

更新时间:2023-11-16 22:13:46

测试静态方法并不比测试任何其他方法不同。其静态方法作为的在另一个测试模块提出问题依赖的(因为它已经提到的 - 你不能嘲笑/提供免费的工具存根它)。但是,如果静态方法本身是单元测试,你可以简单地把它当作工作的,可靠的部件

Testing static method is no different than testing any other method. Having static method as a dependency inside another tested module raises problems (as it's been mentioned - you can't mock/stub it with free tools). But if the static method itself is unit tested you can simply treat it as working, reliable component.

总体而言,没有什么错(如,它不会破坏单元测试/ TDD)与静态方法时:

Overall, there's nothing wrong (as in, it doesn't disrupt unit testing/TDD) with static methods when:


  • 很简单,投入产出法(各种的计算该给的的)

  • 可靠的,按我们的意思是这是由你测试或者单位或来自第三方来源,你认为可靠的(如: Math.Floor 可能会被认为是可靠的 - 使用它不应该提出的你看出来,它是静态的!的警告,人们可能会认为微软,它的工作)

  • it is simple, input-output method (all kinds of "calculate this given that")
  • it is reliable, by what we mean it's either unit tested by you or comes from 3rd party source you consider reliable (eg. Math.Floor might be considered reliable - using it shouldn't raise "Look out, it's static!" warning; one might assume Microsoft does its job)

当静态方法会引起问题,应避免使用?基本上,只有当它们与/ 互动做一些你无法控制(或模拟):

When static methods will cause problems and should be avoided? Basically only when they interact with/do something you cannot control (or mock):


  • 各种文件系统,数据库,网络依赖

  • 其他(可能更复杂)的静态方法从内部调用

  • pretty任何东西嘲弄的框架,不能在普通条件处理

编辑: 何时静态方法的两个例子的做单元测试的硬盘

two examples on when static method will make unit testing hard

1

public int ExtractSumFromReport(string reportPath)
{
     var reportFile = File.ReadAllText(reportPath);
     // ...
}

你如何处理与 File.ReadAllText ?这显然​​会去的文件系统来检索文件的内容,这是重大的没有没有单元测试时。这是一个例子与外部的依赖静态方法。为了避免这种情况,你通常围绕创建文件系统API包装或简单地注入它作为依赖/委托。

How do you deal with File.ReadAllText? This will obviously go to file system to retrieve file content, which is major no-no when unit testing. This is example of static method with external dependency. To avoid that, you usually create wrapper around file system api or simply inject it as dependency/delegate.

2

public void SaveUser(User user)
{
    var session = SessionFactory.CreateSession();
    // ...
}

这个是什么? Session是的非普通的依赖。当然,这可能来作为的Isession ,但怎么做力的SessionFactory 返回模拟?我们不能。我们不能创建的容易detemine 的会话对象无论是。

What about this? Session is non-trivial dependency. Sure, it might come as ISession, but how do force SessionFactory to return mock? We can't. And we can't create easy to detemine session object either.

在类似上述情况下,***完全避免的静态方法。

In cases like above, it's best to avoid static methods altogether.