我只是在玩.NET 4.0的代碼合同,並且必須丟失一些明顯的東西,因爲它們不像我期望的那樣行事。單元測試代碼合同
我一直使用一個簡單的if ... then .. throw語句來在函數的開始處執行任何驗證。
if (hours < 0 || hours > 8)
throw new ArgumentOutOfRangeException("hours", "Hours must be between 0 and 8");
我已經簡單地更換這與
Contract.Requires<ArgumentOutOfRangeException>(hours >= 0 && hours <= 8, "Hours must be between 0 and 8");
,但它似乎永遠不會扔在我的單元測試的問題。
public static DurationUnit HoursAsDuration(int hours)
{
Contract.Requires<ArgumentOutOfRangeException>(hours >= 0 && hours <= 8, "Hours must be between 0 and 8");
switch (hours)
{
case 1:
case 2:
return DurationUnit.Quarter;
case 3:
case 4:
return DurationUnit.Half;
case 5:
case 6:
return DurationUnit.ThreeQuarter;
case 7:
case 8:
return DurationUnit.Full;
default:
return DurationUnit.None;
}
}
[Test]
public void CanConvertToDuration()
{
Assert.AreEqual(DurationUnit.None, DateTimeUtility.HoursAsDuration(0));
Assert.AreEqual(DurationUnit.Quarter, DateTimeUtility.HoursAsDuration(1));
Assert.AreEqual(DurationUnit.Quarter, DateTimeUtility.HoursAsDuration(2));
Assert.AreEqual(DurationUnit.Half, DateTimeUtility.HoursAsDuration(3));
Assert.AreEqual(DurationUnit.Half, DateTimeUtility.HoursAsDuration(4));
Assert.AreEqual(DurationUnit.ThreeQuarter, DateTimeUtility.HoursAsDuration(5));
Assert.AreEqual(DurationUnit.ThreeQuarter, DateTimeUtility.HoursAsDuration(6));
Assert.AreEqual(DurationUnit.Full, DateTimeUtility.HoursAsDuration(7));
Assert.AreEqual(DurationUnit.Full, DateTimeUtility.HoursAsDuration(8));
//Would expect this to cause an issue
Assert.AreEqual(DurationUnit.None, DateTimeUtility.HoursAsDuration(9));
}
該測試返回true,但我會預期代碼合同停止進入switch語句的「9」的值。這是預期的行爲?
感謝帕斯卡爾,它確實清除了一些東西。我認爲代碼合同可以取代所有參數檢查,但如果我希望他們在生產版本中,他們仍然需要保留。 – fluent 2011-03-03 09:08:34
更新:下面的Porges指出我正確的方向,編輯項目設置以啓用生產版本中的合同。 – fluent 2011-03-03 09:18:30