1

My goal is static contract checking to catch / avoid passing around nulls, and I'm new to contracts.

I'm using Contract.Requires(param!=null) in a method (Link ctor) and as a test, I call it with null parameters, and I expect it to warn me, but it does not.

The unit test passes, so runtime behavior is as expected.

Why isn't it warning me of the nulls going into the function that can't take nulls?

Class under test:

using System.Diagnostics.Contracts;

public class Link
{

    private readonly Shape origin;

    private readonly Shape destination;
    public Link(Shape origin, Shape destination)
    {
        Contract.Requires<ArgumentException>(origin != null);
        Contract.Requires<ArgumentException>(destination != null);
        this.origin = origin;
        this.destination = destination;
    }

    public string OriginID()
    {
        return origin.ID;
    }

    public string DestinationID()
    {
        return destination.ID;
    }

}

Unit Test:

    using Moq;
    using NUnit.Framework;
    using Simmons.UI.Controls.Diagram;

    namespace Unit
    {
        /// <summary>
        /// A test class for Link
        /// </summary>
        [TestFixture()]
        public class LinkShould
        {
          private Link link;

          [Test()]
          [ExpectedException(typeof(ArgumentException))]
          public void ExplodeWhenLinkIsCreatedWithNulls()
          {
            //set up
            link = new Link(null, null); // No warning on this line
          }    
    }

And here are my settings in the test project: enter image description here

toddmo
  • 20,682
  • 14
  • 97
  • 107
  • Should the code be `Link link= new Link(null, null);`? You missed the instance. –  Mar 11 '15 at 01:28
  • Yes, for the example, it should be. I'll change my example. In my code it's declared elsewhere and I forgot and left that out. – toddmo Mar 11 '15 at 14:55

1 Answers1

0

For static checks to work, you need to explicitly enable them in Project Properties / Code Contracts tab. There is a whole section with checkboxes dedicated to configuring static checking.

In your case, make sure it is enabled for the project that holds the Link class.

alex
  • 12,464
  • 3
  • 46
  • 67