Archive for May, 2013

Cleaning Up with MSpec

I use MSpec for testing my code.  I love the behavior driven approach, for me it just makes sense.  I love how if my boss asks where are we with component XYZ, I can just run all my tests and give him the output.  It shows what’s working and what’s not.  Further more, we can say or make a rule that software doesn’t have a feature until there’s an mspec test saying that it does.

I was recently working with mspec doing integration tests – these I usually do to make sure my DAL and my database are structurally compatible – and I kept getting database constraint errors when I reran tests.  It didn’t make a lot of sense as I had a cleanup section in my code and I wasn’t seeing any errors.

It turns out, that if an exception is thrown in the cleanup section you’ll never hear about it.  At least for me, it doesn’t bubble up.  Once I put a breakpoint on the first line of the cleanup I figured it out.  Previously I was thinking it wasn’t even hitting my cleanup code.  It was hitting the cleanup section however, only there was an error in that section.  Hopefully this gets into the googles and helps someone.

using Machine.Specifications;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace My.Project.Integration.Tests
{
    public class when_creating_a_mything_record
    {
        protected static IMyThingService MyThingService { get; set; }

		protected static MyThing MyThing { get; set; }
		protected static MyThing SavedMyThing { get; set; }

		Establish context = () =>
        {
            MyThing = new MyThing() {
				Name = "thing",
				Description = "thing one"
			};
			MyThingService = ServiceLocator.Instance.Locate<IMyThingService>();
        };

        Because of = () => Exception = Catch.Exception(() =>
        {
            SavedMyThing = MyThingService.Insert(MyThing);
        });

        It should_not_have_thrown_an_exception = () => Exception.ShouldBeNull();
        It should_have_an_id_that_does_not_match_guid_empty = () => SavedMyThing.ID.ShouldNotEqual(Guid.Empty);

        Cleanup after = () =>
        {
           // If this does not appear to get called. put a breakpoint here.  You may have an exception.
           MyThingService.Delete(SavedMyThing);
        };
    }
}

Advertisements

Leave a comment