2008-11-11 24 views

回答

4

你可能想看看那生命不息約束對象的「內」的方法。

例如:

Assert.That(DateTime.Now, Is.EqualTo(DateTime.Now.AddMilliseconds(1000)).Within(101)); 

它通常用來給一個寬容雙打和花車,但由於在最後一個DateTime是一個雙,它可能會滿足您的需求。

1

將您的容差轉換爲Ticks,然後使用And約束。就像是;

long ticks = mydate.Ticks; 
long tolerance = 1000; 
Assert.That(ticks, Is.LessThan(ticks + tolerance) & Is.GreaterThan(ticks - tolerance)); 

我想創建一個擴展方法或您自己的斷言來,雖然做到這一點。

1

從另一箇中減去一個TimeSpan值,使用TotalXYZ屬性(如TotalMilliseconds)獲取值,使用Math.Abs​​將其轉換爲總是正值,然後檢查您的值公差值。

舉例來說,如果他們需要在10毫秒內相互的:

if (Math.Abs((dt1 - dt2).TotalMilliseconds) <= 10) 
{ 
    CloseEnough(); 
} 
2
TimeSpan tolerance = new TimeSpan(0,1,0); // e.g. 1 minute 

Assert.IsTrue((firstDateTime-SecondDateTime).Duration() > tolerance); 
相關問題