基于今天的日期进行日期处理的单元测试代码 [英] Unit testing code that does date processing based on today's date

查看:13
本文介绍了基于今天的日期进行日期处理的单元测试代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当代码根据当前日期处理日期时,测试应涵盖边缘情况,例如闰年以及更频繁的月份和年份边界.

When code processes dates based on the current date, testing should cover edge cases such as leap years as well as the more frequent month and year boundaries.

在我们的代码中,我们总是使用 DateTime.Now(在我们的例子中为 .NET)在我们的类中深入获取当前日期.

In our code we always get the current date deep down in our classes using DateTime.Now (.NET, in our case).

你如何对这样的代码进行单元测试?

How can you unit test such code?

这是依赖注入变得非常有用的地方吗?

Is this where Dependency Injection becomes very useful?

这是一个小问题,但显然下一个版本的 Typemock 将允许伪造 DateTime.Now

This is a slight aside, but apparently the next version of Typemock will allow faking of DateTime.Now

https://blog.typemock.com/2009/05/mockingfaking-datetimenow-in-unit-tests.html

推荐答案

在我们的代码中,我们总是使用 DateTime.Now(在我们的例子中为 .NET)提取当前日期.您如何对此类代码进行单元测试?

In our code we always pull out the current date using DateTime.Now (.NET, in our case). How can you unit test such code?

这是一个依赖项,并且是一个非确定性的依赖项.您需要将代码的职责再细分一点.

This is a dependency, and a non-deterministic dependency at that. You need to divide the responsibility of the code up a little more.

之前:

  • 有一些代码使用当前日期时间来做 X.

之后:

  • 应该有一些代码负责获取当前日期时间.
  • 应该有一些代码使用日期时间来做 X.

这两套代码不应该相互依赖.

These two sets of code should not be dependent on each other.

这种分离依赖项的模式也适用于其他情况(数据库、文件系统等).

This pattern of seperating dependencies works for other cases as well (database, filesystem, etc).

这篇关于基于今天的日期进行日期处理的单元测试代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆