单元测试中当前日期问题的模式
是否有一个常见的知识模式或习惯用法来解决使用 new Date() 的代码极难进行单元测试的问题?
我知道一个可能的解决方案(例如 http: //refactoringaspnet.blogspot.com/2010/02/unit-testing-code-which-is-dependent-on.html),但问题是这个问题是否有通用的模式和语言。
Is there a common knowledge pattern or idiom to solve the problem that code that uses new Date() is extremely hard to unit-test?
I know a possible solution (e.g. http://refactoringaspnet.blogspot.com/2010/02/unit-testing-code-which-is-dependent-on.html), but the question is whether there is a common pattern and language for this problem.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我有时做的是构建一个负责返回日期的接口。
例如:
如果单元测试需要,可以模拟它。
What I sometimes do is build an Interface that is responsible for returning the date.
for example:
this could then be mocked out if required for unit tests.
这个想法是简单地将任何难以测试的东西(即难以控制单元测试的目的)移到界面后面。接下来使用 Fake 或 Mock 来为您提供所需的控制。
您在问题中链接的博文在很大程度上是正确的。但是,我个人不会创建实例化依赖项的 TestableClock 的最后一点。我更愿意将它作为构造函数参数或方法参数传递。
The idea is to simply move anything that is difficult to test (i.e. difficult to control for the purposes of unit testing) behind an interface. Follow that up with a Fake or a Mock which gives you the required control.
The blogpost that you linked in the question is right for the most part.. However I personally wouldn't do the last bit of creating a TestableClock which instantiates the dependency. I'd prefer to pass it in as a ctor argument or a method parameter.
如果我没有错误地理解您的需求,那么您正在寻找“嘲笑”:
这为一些不属于测试一部分的底层代码提供了一个假实现,但它必须正常工作才能成功测试某些逻辑。
If I don't understood wrongly your needs, you're looking for "mocking":
That's providing a fake implementation for some underlying code that's not part of the test, but it must work properly in order to successfully test some logic.
就是这样。你必须模仿/伪造当时的阅读。这可以超出系统时间。您可以拥有一个通用的“环境”界面,使您能够控制测试的其他非确定性因素。
That is it. You'll have to mock/fake the reading of the time. This can extend beyond just the system time. You could have a general "environment" interface that allows you to gain control over other non-deterministic factors for your testing.