0
public void DoSomethingAccordingToYear()
{
if(DateTime.Now.Year < 2010)
DoSomething();
else
DoSomethingElse();
}
我想测试这种方法。 如何在不更改我的代码并且不使用接口的情况下模拟DateTime ?嘲笑DateTime
public void DoSomethingAccordingToYear()
{
if(DateTime.Now.Year < 2010)
DoSomething();
else
DoSomethingElse();
}
我想测试这种方法。 如何在不更改我的代码并且不使用接口的情况下模拟DateTime ?嘲笑DateTime
这样做的一种常见方式是传入获取日期的组件。例如:
public interface IDateTimeNowProvider
{
DateTime Now { get; }
}
public class DateTimeNowProvider : IDateTimeNowProvider
{
public DateTime Now => DateTime.Now;
}
现在你可以注入一个IDateTimeNowProvider
到你的对象,模拟该网址。
如果您改变方法的定义,它是简单的:
public void DoSomethingAccordingToYear(DateTime testDate)
{
if(testDate.Year < 2010)
DoSomething();
else
DoSomethingElse();
}
然后调用它像这样:
// production
DoSomethingAccordingToYear(DateTime.Now);
// test
DoSomethingAccordingToYear(new DateTime(2009,1,1));
编辑
如果你不想改变你调用方法的方式,你也可以像这样实现它:
public void DoSomethingAccordingToYear(DateTime? testDate = null)
{
testDate = testDate ?? DateTime.Now;
if (testDate.Year < 2010)
DoSomething();
else
DoSomethingElse();
}
如果您不带参数调用它,那么它将使用DateTime.Now
,但您仍然可以传递参数进行测试。
改变你的电脑上的时间? – BugFinder
这些选项都不允许你自动运行测试,请不要这样做! – DavidG
也@TejashwiKalpTaru'DateTime'对象是不可变的,你不能改变它。 – DavidG