单元测试中当前日期问题的模式

发布于 2024-10-16 03:30:35 字数 314 浏览 2 评论 0原文

是否有一个常见的知识模式或习惯用法来解决使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

小ぇ时光︴ 2024-10-23 03:30:35

我有时做的是构建一个负责返回日期的接口。
例如:

public interface ISystemClock
{
    DateTime GetCurrentDate();
}

如果单元测试需要,可以模拟它。

What I sometimes do is build an Interface that is responsible for returning the date.
for example:

public interface ISystemClock
{
    DateTime GetCurrentDate();
}

this could then be mocked out if required for unit tests.

思慕 2024-10-23 03:30:35

这个想法是简单地将任何难以测试的东西(即难以控制单元测试的目的)移到界面后面。接下来使用 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.

沩ん囻菔务 2024-10-23 03:30:35

如果我没有错误地理解您的需求,那么您正在寻找“嘲笑”:

这为一些不属于测试一部分的底层代码提供了一个假实现,但它必须正常工作才能成功测试某些逻辑。

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.

汐鸠 2024-10-23 03:30:35

就是这样。你必须模仿/伪造当时的阅读。这可以超出系统时间。您可以拥有一个通用的“环境”界面,使您能够控制测试的其他非确定性因素。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文