title: Unit testing code contracts
body: <p>I'm just having a play with the code contracts in .Net 4.0 and must be missing something obvious as they are not behaving as I would expect.</p>
  
  <p>I have always used a simple if... then.. throw statement to perform any validation at the start of a function.</p>
  
  <pre><code>if (hours &lt; 0 || hours &gt; 8)
      throw new ArgumentOutOfRangeException("hours", "Hours must be between 0 and 8");
  </code></pre>
  
  <p>I have simply replaced this with</p>
  
  <pre><code>Contract.Requires&lt;ArgumentOutOfRangeException&gt;(hours &gt;= 0 &amp;&amp; hours &lt;= 8, "Hours must be between 0 and 8");
  </code></pre>
  
  <p>but it never seems to throw an issue on my unit tests.</p>
  
  <pre><code>    public static DurationUnit HoursAsDuration(int hours)
      {
          Contract.Requires&lt;ArgumentOutOfRangeException&gt;(hours &gt;= 0 &amp;&amp; hours &lt;= 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));
      }
  </code></pre>
  
  <p>The test returns true but I would have expected the code contract to stop the value of "9" getting into the switch statement. Is this the expected behaviour?</p>