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

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

问题描述

当代码处理按照当前日期进行日期时,测试应该涵盖边缘案例,例如闰年以及更频繁的月份和年份边界。

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 (在我们的例子中)获取当前日期。

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

http://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。

之后:


  • 应该有一些代码负责获取当前的日期时间。

  • 应该有一些代码使用datetime来做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天全站免登陆