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);
            }
        }
    }

Don’t copy-and-paste code. Don’t use debug driven development!

I see a common copy-and-paste trend specially with junior developers. Many of them just copy-and-paste random internet code into their projects. After a while I ask them about their implementation… very few understand what they copy-and-paste and the implications of that implementation!

I inquired further and it was clear that many used debug driven development to get the copy-and-paste code to work. Debug driven development is basically 90% random changes and 10% thinking. This is a popular trend within .NET developers with visual studio because the IDE is amazing…very little planning is required to get things to work.

After a few weeks of seeing this trend I did the following:

If they asked me a question that I believe is due to copy-and-paste or debug driven development I reply with the following questions

  1. Did you google the problem? (some  of them didn’t google the problem!)
  2. Did you copy and paste code? Is that code giving you the error? If you did copy and paste, what does the code do?
  3. What are 2 different approaches to this implementation and why did you choose this implementation?

After answering the questions above, they were able to solve the problems themselves. That makes them happy and it makes me happy!

Dynamic Azure Web Services URLs

I am currently building a lot of web services for Azure. Since URLs change a lot in development and deployment environments I needed to be able to have those services URLs updated dynamically. The easiest way I found is using handlers and:


HttpContext.Current.Request.Headers["Host"];

This way none of the URLs get hard-coded and deployment is extremely easy. This also brings a lot of neat options for Intercloud communication, but that is for another post.

The build process

  • Ensure Binary Integrity of your build:
    • The build either works or it does not work. This way it is easier to rule out errors in different layers of the project like database or logic
  • Builds are obtained from files under source control:
    • This means that if a problem happens the error can be linked to a specific commit or tag under version control
  • Build can happen remotely (production) or locally:
    • This allows for the same local configuration to be tested on different environments remotely (production)
    • It can also allow specific special configuration (ex: a tag under version control) to be propagated to production
    • Basically helps prevent configuration errors by removing as much as possible the human aspect
  • All builds should contain a database script (under version control) that creates/restores the database  from scratch
    • This way each database change is linked to a version under version control and errors can be linked to each build
    • Also this makes finding bugs a lot easier as they are easier to reproduce

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.