更新时间: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
可能会被认为是可靠的 - 使用它不应该提出的你看出来,它是静态的!的警告,人们可能会认为微软,它的工作)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):
编辑: 何时静态方法的两个例子的会做单元测试的硬盘的
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.