UnitTest一种与时间有关的方法 [英] UnitTest a method that is time-dependent

查看:87
本文介绍了UnitTest一种与时间有关的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您如何测试与时间相关的方法?

How would you test a method that is time-dependent?

一个简单的示例可能是:

A simple example could be:

public static int GetAge(DateTime birthdate)
{
    // ...
}

[TestMethod]
public void GetAgeTest()
{
    // This is only ok for year 2013 !
    Assert.AreEqual(GetAge(new DateTime(2000, 1, 1)), 13);
}

问题在于它仅在当年(2013年案件)。新年伊始,我必须重写所有与时间相关的测试...

The problem is that it will work only for the current year (2013 in this case). As soon as a new year begins, I have to rewrite all time-dependent tests...

对这种方法进行单元测试的最佳方法是什么?

What is the best approach to Unit Test such a method?

推荐答案

两个主要选项:


  1. 创建隔离时间相关功能的服务,并将其接口注入需要它的类中。然后,您可以模拟该接口以获取测试所需的行为。

  1. Create a service that isolates time-dependent functionality and inject its interface into classes that need it. Then you can mock this interface to get the behavior you need for testing.

使用绕行测试框架,例如摩尔(那里还有其他一些)可以重新路由静态方法调用,例如 DateTime.Now

Use a detouring test framework like Moles (there are a few others out there, as well) that can reroute static method calls like DateTime.Now.

这篇关于UnitTest一种与时间有关的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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