Testing Code Contracts .NET 4.0

Why use Code Contracts?

By providing pre-compiled code contract interfaces other developers can adhere to signatures and also expected behavior. This is specially important due to the Liskov substitution principle.

Dino Esposito wrote a great article on the topic called Code Contracts Preview: Interfaces.

Testing

To test that all the right contracts are in place a test project can be created.

Testing preconditions is possible by catching the exceptions created by those preconditions.


        [TestMethod]
        [ExpectedException(typeof(ArgumentOutOfRangeException))]
        public void ModelNegativeBlance()
        {
            Account acc = new Account()
            {
                AccountName = "NewAccount",
                //0 or positive is expected
                Balance = -99,
                CreationDate = DateTime.Now

            };
        }

Testing postconditions is a bit tricky because the exceptions raised by postconditions are not meant to be caught. Therefore plain strings have to be used.


    public static class TestHelpers
    {
        public static string ContractExceptionName = "System.Diagnostics.Contracts.__ContractsRuntime+ContractException";

    }
    public class RepositoryTests
    {
        public RepositoryTests()
        {

        }

        [TestMethod]
        public void InsertModelWithNoParitionKeyDueToBadRepository()
        {

            var repo = SetBadRepo();
            Account acc = new Account()
            {
                AccountName = "NewAccount",
                Balance = 0,
                CreationDate = DateTime.Now

            };

            try
            {
                repo.InsertAccount(acc);
            }
            catch (Exception ex)
            {
                Assert.AreEqual(TestHelpers.ContractExceptionName, ex.GetType().FullName);
            }
        }
    }

Value Objects in F#

Value Objects are objects that can be shared across different parts of a program. This can have great benefits in performance. Because  the objects are shared it is very important for value objects to be immutable. If value objects are not immutable then any part of the program can change the values and all the other parts can do calculation with erroneous data.

One of my goals was to make immutable objects in F# to take advantage of parallelization and automatic compiler optimizations:


type City(Name:string, X: float, Y:float) =

member t.Name = Name

member t.X = X

member t.Y = Y

type NeighborCities(city1:string, city2:string) =

member x.fromCity = city1

member x.toCity = city2

Objects created in this manner in F# are immutable. Even when they are accessed in other projects outside their definition, their members are read-only. This was specially helpful on the distributed traveling salesman problem I built last year.

Unitiy IOC

Basically, with Unity, I ended up writing something like this (simplified version) :

IUnityContainer container = new UnityContainer();

container.RegisterType<IRiskRepository, RiskRepository>();

string conn = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;

container.Configure<InjectedMembers>().ConfigureInjectionFor<RiskRepository>(new InjectionConstructor(conn));

UnityControllerFactory factory = new UnityControllerFactory(container);

ControllerBuilder.Current.SetControllerFactory(factory);

Unity turned out to work very well. I was able to save a lot of lines of code and it is greatly improving the testability of the dynamic modules I am using on the mock project architecture. Also, it was easy to set up. Its a good alternative to the other more popular IOC.