驗證 DateTimeHelper.GetRandomTime 在極端邊界 (DateTime.MinValue/MaxValue) 與參數順序互換時,產生的隨機時間皆落於指定範圍內。
using System;
using NUnit.Framework;
namespace Yyw
{
[TestFixture]
public class DateTimeHelperFixture
{
[Test]
public void TestGetRandomTime()
{
DateTime min = DateTime.MinValue;
DateTime max = DateTime.MaxValue;
Random rnd = new Random();
// 參數順序: (max, min)
for (int i = 0; i < 10000; i++)
{
DateTime rt = DateTimeHelper.GetRandomTime(max, min, rnd);
CheckResult(min, max, rt);
}
// 參數順序: (min, max)
for (int i = 0; i < 10000; i++)
{
DateTime rt = DateTimeHelper.GetRandomTime(min, max, rnd);
CheckResult(min, max, rt);
}
}
private void CheckResult(DateTime min, DateTime max, DateTime rt)
{
TimeSpan ts1 = new TimeSpan(rt.Ticks - min.Ticks);
TimeSpan ts2 = new TimeSpan(rt.Ticks - max.Ticks);
Assert.IsTrue(ts1.TotalSeconds >= 0 && ts2.TotalSeconds <= 0);
}
}
}
Ticks 精確比較時間範圍,避免 Seconds 屬性只回傳秒數部分的誤區。min/max 互換邏輯。[Repeat(100)] 屬性簡化迴圈。Random 種子固定情況下的可重現性。DateTime.Kind (Local/Utc/Unspecified) 驗證時區處理正確性。