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