Wednesday, August 13, 2014

Why are my form values being cached after the first POST?

Here is the controller source code:

and here is the view code:

Run the code and submit the form. Notice after the first submit, the value in the textbox will change from 0 to 1. Upon subsequent POST’s though, that value won’t change from 1. Why is that?

I ran into this oddity earlier today and did some research, but it wasn’t until a colleague of mine found a key bit of knowledge that the puzzle was solved. During my findings, I noticed many people trying to solve “form values cached after POST” by setting the attribute autocomplete=”off”. Specifically that attribute is placed on the <input>, or even the <form> (due to how different browsers handle this attribute, you may need to place it on <form>, since it may not work otherwise). However in my case, regardless of there being an autocomplete attribute on my <form>, the form values were still cached. Huh?

As a plan B, I tried the following view instead:

This time, when I POST the form, the textbox value increments as expected – 0, 1, 2, 3… etc. So why does this work, whilst using the HTML helper method TextBoxFor resulted in cached values? It’s all to do with ModelState.

When Html.TextBoxFor() (or Html.TextBox()) executes, it merges values from the ModelState back into the view. It does this so that if there is a validation error, the value causing the error is rendered on the page. In other words, the old value is used, not the new value that is passed from the action method. This was very confusing at first, but if you think about it, it does make sense. If this did not happen, then you’d get validation errors shown, but with the wrong values being highlighted as the problem.

You can get around this by removing a value from ModelState:

In the above example, “Number” will no longer be merged from ModelState when the view is rendered.

Saturday, June 14, 2014

Unit Test Object Builder – Enter the Expando!

Whilst reading the rather brilliant book Growing Object-Oriented Software, Guided By Tests, I saw an interesting example of using a builder pattern for creating object instances. Here’s a example:

Customer customer = new CustomerBuilder().WithFirstName(“John”).Build();

A builder object can take care of initializing object instances, or even create a list of those object instances. Take a look at nBuilder for an example of a great framework that does just that. What caught me out was the method “WithFirstName”. Interesting; the property “FirstName” appears in the method name. Previously I had seen objects initialized similar to the following

Customer customer = Builder<Customer>.CreateNew().With(c => c.FirstName = "John").Build();

This got me thinking – having just played around with ExpandoObject I decided to have a got at replicating the CustomerBuilder seen in the Growing Objects book. Here’s my attempt:

public static class ObjectChauffeur
{
    public static dynamic Create<T>()
    {
        var result = new ExpandoObject() as IDictionary<string, object>;

        var targetType = typeof(T);

        var targetInstance = Activator.CreateInstance<T>();

        PropertyInfo[] properties = targetType.GetProperties(BindingFlags.Public | BindingFlags.Instance);

        foreach (var prop in properties)
        {
            Func<object, object> targetAction = (param) =>
            {
                prop.SetValue(targetInstance, param, null);

                return result;
            };

            result.Add(string.Concat("With", prop.Name), targetAction);
        }

        CreateBuildFunciton(result, targetInstance);

        return result;
    }

    private static void CreateBuildFunciton<T>(IDictionary<string, object> expando, T instance)
    {
        Func<T> buildFunc = () => instance;

        expando.Add("Build", buildFunc);
    }
}

Before I explain what’s going on, this sample illustrates how to use the above class. First, let’s create a Person object:

public class Person
{
    public int Age { get; set; }

    public string FirstName { get; set; }

    public IList<int> Numbers { get; set; }

    public string Surname { get; set; }

    public override string ToString()
    {
        return string.Concat(this.FirstName, " ", this.Surname, " is ", this.Age);
    }
}

Now, let’s get the chauffer to build an instance of Person:

Person person = ObjectChauffeur.Create<Person>()
    .WithFirstName("Jason")
    .WithSurname("Evans")
    .WithAge(36)
    .WithNumbers(new List<int>() { 1, 2 })
    .Build();

Review the ObjectChauffer class and, specifically, look at the method Create<T>(). It basically uses reflection to iterate through all the public properties of the type T. For each property name the word “With” is prepended. Finally, since ExpandoObject implements IDicitonary<string, object>, we can add the property name and it’s value to an internal dictionary that is returned as the dynamic object.

Admittedly this isn’t the most practical “helper” class ever built, certainly the lack of intellisense when you start typing “With”, and not knowing property names of the target type off hand, will be annoying. But hey, I thought it was an interesting experiment at least.

Saturday, June 07, 2014

Access XML data using ExpandoObject

I haven’t dabbled much with any of the dynamic features available in the .NET Framework, but I recently came across this very handy technique of using ExpandoObject to iterate, and access, XML data a lot cleaner. Let’s use the following XML

<?xml version="1.0" encoding="utf-8" ?>
<Employees>
  <Employee>
    <FirstName>Jason</FirstName>
  </Employee>
  <Employee>
    <FirstName>Mark</FirstName>
  </Employee>
</Employees>

Using an XDocument, we would need to write the following code to iterate through each employee

var doc = XDocument.Load("XmlFile1.xml");

foreach (var element in doc.Element("Employees").Elements("Employee"))
    Console.WriteLine(element.Element("FirstName").Value;

This is how I, and I assume many other devs, have gone about accessing XML data inside an XDocument. So here’s a neater way – an extension method that will do the hard work for us

public static class ExpandoXml
{
    public static dynamic AsExpando(this XDocument document)
    {
        return CreateExpando(document.Root);
    }

    private static dynamic CreateExpando(XElement element)
    {
        var result = new ExpandoObject() as IDictionary<string, object>;

        if (element.Elements().Any(e => e.HasElements))
        {
            var list = new List<ExpandoObject>();

            result.Add(element.Name.ToString(), list);

            foreach (var childElement in element.Elements())
                list.Add(CreateExpando(childElement));
        }
        else
        {
            foreach (var leafElement in element.Elements())
                result.Add(leafElement.Name.ToString(), leafElement.Value);
        }

        return result;
    }
}

Taking in an XDocument, the extension method will iterate through all the XElements, and each child element of those, building up a hierarchy of ExpandoObjects. This provides us the ability to access the XML like so

 var doc = XDocument.Load("XmlFile1.xml").AsExpando();

 foreach (var employee in doc.Employees)
     Console.WriteLine(employee.FirstName);

That looks much better.

Tuesday, February 07, 2012

Example of Builder Design Pattern

I happened to come across an interesting idea from a Java blogger regards the Builder design pattern. For those of you who are not familiar with this pattern, check out the Wikipedia explanation. Check out this code:

    public class Address
    {
        public string Protocol { get; set; }
        public string Description { get; set; }
        public int Port { get; set; }
        public string Path { get; set; }
        public string Url { get; set; }

        private Address(AddressBuilder addressBuilder)
        {
            this.Protocol = addressBuilder._protocol;
            this.Url = addressBuilder._url;
            this.Port = addressBuilder._port;
            this.Path = addressBuilder._path;
            this.Description = addressBuilder._description;
        }

        public interface IBuild
        {
            Address Build();
            IBuild Description(string description);
            IBuild Path(string path);
            IBuild Protocol(string protocol);
        }

        public interface IPort
        {
            IBuild Port(int port);
        }

        public interface IUrl
        {
            IPort Url(string url);
        }

        public static IUrl Builder()
        {
            return new AddressBuilder();
        }

        public class AddressBuilder : IUrl, IBuild, IPort
        {
            public string _description;
            public string _path;
            public int _port;
            public string _protocol;
            public string _url;

            public Address Build()
            {
                return new Address(this);
            }

            public IBuild Description(string description)
            {
                this._description = description;
                return this;
            }

            public IBuild Path(string path)
            {
                this._path = path;
                return this;
            }

            public IBuild Port(int port)
            {
                this._port = port;
                return this;
            }

            public IBuild Protocol(string protocol)
            {
                this._protocol = protocol;
                return this;
            }

            public IPort Url(string url)
            {
                this._url = url;
                return this;
            }
        }
    }

Now there’s a lot going on here, but lets see what the above code allows us to do:

var address = Address.Builder()
    .Url("ddd")
    .Port(23)
    .Build();

We can build an Address instance using the Builder pattern, which has this nice fluent API to it. The key idea is that, since port and url are mandatory fields, we have designed the builder in such a way that those fields must be given a value before the “Build()” method can be called. If you look at the code you’ll see that this is achieved by having a nested “Builder” class that implements private interfaces associated with the Address object. The method “Address.Builder()” returns a new Builder instance via the IUrl interface. That interface has a “Port” method which must be called. The Port method returns an IBuild interface which has the “Build()” method which will actually create the Address instance.

Have a play around with this code, I think it’s a very nice way to create objects whilst making it clear which properties are mandatory.

Monday, November 21, 2011

The Agile Testing & BDD eXchange 2011

Check out these videos taken from the recent The Agile Testing & BDD eXchange. You'll find talks on topics such as:

- BDD
- Living Documentation
- Testing

I know what I'll be watching tonight :) (Coffee? (Check), Biscuits? (Check), Slippers? (Check))

Sunday, November 20, 2011

KnockoutJS 1.3 Almost Here

For those of you who are fans of Steve Sanderson’s excellent MVVM (Model View View Model) framework KnockoutJS, you'll be pleased to hear that the release candidate for version 1.3 is now available. There are a number of improvements including better syntax for defining event handling (a popular fix for many people who felt that the current method of event binding was a bit messy).

Check out this blog article by Steve, which talks about the upcoming changes.

Saturday, November 19, 2011

Using MSpec.Fakes–Part 2

Next example I’d like to show is how to force a method to return a specific value:

public class example_when_told_to : WithFakes
{
    private static int result;
    private static IHelper sut;

    private Establish context = () =>
        {
            sut = An<IHelper>();
            sut.WhenToldTo(s => s.OK(Arg<int>.Is.Anything)).Return(4567);
        };

    private Because of = () => result = sut.OK(1);

    private It should_be_4567 = () => result.ShouldEqual(4567);
}

Here I use ‘WhenToldTo()’ in order to control the return value of ‘OK()’. I could also do this:

public class example_when_told_to : WithFakes
{
    private static int result;
    private static IHelper sut;

    private Establish context = () =>
        {
            sut = An<IHelper>();
            sut.WhenToldTo(s => s.OK(23)).Return(4567);
        };

    private Because of = () => result = sut.OK(23);

    private It should_be_4567 = () => result.ShouldEqual(4567);
}

So when ‘OK()’ is called with a specific argument, in this case 23, I want to return the value 4567. OK, so let’s have a look at using the ‘WithSubject’ parent class. First, we need the code for the salary calculator which Helper is using:

public interface ISalaryCalculator
{
    double CalculateSalary(double baseSalary, double bonus);

    int GetValue();
}

public class SalaryCalculator : ISalaryCalculator
{
    public double CalculateSalary(double baseSalary, double bonus)
    {
        return baseSalary + bonus;
    }

    public int GetValue()
    {
        return 34;
    }
}

Now here is the example test class we’ll be referencing:

public class example_using_WithSubject_1 : WithSubject<Helper>
{
    private static int result;

    private Establish context = () => The<ISalaryCalculator>().WhenToldTo(x => x.GetValue()).Return(1);

    private Because of = () => result = Subject.OK(1);

    private It should_be_1 = () => result.ShouldEqual(1);
}

We’re using WithSubject and passing it the type of Helper. What this give us is a .Subject property that we can use to access the SUT (i.e. the instance of Helper). The other cool thing is that since Helper requires an implementation of ISalaryCalculator in it’s constructor, an instance of ISalaryCalculator will be created for us. Not only that, but we can control the behaviour of the ISalaryCalculator instance via the ‘The<>’ method.

In the above example I’m stating that when ISalaryCalculator.GetValue() is called, it should return 1. We can also verify calls against the ISalaryCalculator like this:

public class example_using_WithSubject_2 : WithSubject<Helper>
{
    private static int result;

    private Because of = () => result = Subject.OK(1);

    private It should_be_1 = () => The<ISalaryCalculator>().WasToldTo(x => x.GetValue());
}

That’s all for now. I might write a bit more about using Stubs in your MSpec.Fakes tests for part 3.

Thursday, November 17, 2011

Using MSpec.Fakes–Part 1

I decided to try out MSpec.Fakes, just to see how it works and to write a very quick guide on how to use it. First, in Visual Studio 2010, I added a reference to MSpec.Fakes via NuGet:

Nuget

I chose the RhinoMocks flavour mainly as I had dabbled with both it and Moq in the past and felt that RhinoMock annoyed me less Smile (Note: I’m a TypeMock user by heart, but I often have to use an open source mocking framework, in order that all devs on the team can run the tests. TypeMock does have it’s critics, but it’s by far my choice of isolation framework, but that’s for another post.)

OK, once installed, I created a couple of nonsense classes and interfaces in order to help me get up and running:

public interface IHelper
{
    int OK(int number);
}

public class Helper : IHelper
{
    private readonly ISalaryCalculator salaryCalculator;

    public Helper(ISalaryCalculator salaryCalculator)
    {
        this.salaryCalculator = salaryCalculator;
    }

    public int OK(int number)
    {
        return this.salaryCalculator.GetValue();
    }
}

Here’s my MSpec test, I’ll explain what’s going on next:

public class when_given_a_number : WithFakes
{
    private static int result;
    private static IHelper sut;

    private Establish context = () => { sut = An<IHelper>(); };

    private Because of = () => result = sut.OK(1);

    private It should_have_been_passed_a_number = () => sut.WasToldTo(s => s.OK(Arg<int>.Is.Anything));
}

Notice that the test class inherits WithFakes, this parent class has the support for the faking implementation. The cool thing is that, regardless of the underlying mocking framework you choose to use (Moq, RhinoMock) the MSpec.Fakes API is the same. I really like this approach. Next thing to look at is how we create an instance of the Subject Under Test (SUT)

private Establish context = () => { sut = An<IHelper>(); };

The An<>(); method takes care of calling the RhinoMock equivalent of

var mockRepository = new MockRepository();
var helperMock = mockRepository.CreateMock<IHelper>();

After calling the .OK() method, the assertion for this test is that sut.OK() was called with any number:

private It should_be_1 = () => sut.WasToldTo(s => s.OK(Arg<int>.Is.Anything));

Here we see the .WasToldTo() method which takes care of verifying that .OK() was indeed called with any number. Simples.

In my next post I will show some more examples.

Friday, November 11, 2011

Using Jing To Record Videos

For the past few weeks I have been using Jing, a screencast tool available from TechSmith. Jing comes in two flavours: Free and Pro. I use the free edition. If you purchase the Pro version you do get the ability to save videos in MPEG-4 format (the free edition only allows you to create SWF files).

I learnt about Jing after reading this blog article on the Telerik site. They use Jing to record the progress of features completed by developers. This provides instant feedback to the team on how a feature has been implemented. I really like that idea and started to use it at work, though I’ve been recording videos to help document how I resolved some customer issues which are reported to us. I’ve also recorded videos which show how to configure IIS for client who wanted 301 redirects for certain url’s on their site. The videos have proved really useful, no to mention the amount of time saved when compared to writing out documentation by hand!

Tuesday, August 16, 2011

Getting Ready For Windows 8

It doesn’t feel all that long ago when Windows 7 was released. Now, Microsoft are getting ready to introduce the world to Windows 8. Check out the Building Windows 8 blog where MS will be posting allsorts about the next OS. Back in 2008 MS began writing about Windows 7 using the same blog, which proved very popular, so they have decided to repeat this idea. Considering the lack of detail MS have thus far released about Windows 8, I’m sure many people will regularly keeping an eye on the new blog!

Saturday, August 13, 2011

When Are The Letters “F” and “G” Are Considered Equal

A friend of mine noticed an unusual anomaly whilst writing a .NET app which was using the Welsh (cy-GB) culture. Here’s a snippet:

public class Program
{
    static void Main(string[] args)
    {
        var cultureInfo = new CultureInfo("cy-GB");

        Thread.CurrentThread.CurrentCulture = cultureInfo;
        Thread.CurrentThread.CurrentUICulture = cultureInfo;

        Console.WriteLine(String.Equals("f", "g", StringComparison.CurrentCultureIgnoreCase));
        Console.ReadLine();
    }
}
You would expect “f” and “g” to be different, however in this universe they are considered the same! A quick rummage around the Google attic revealed this Microsoft Connect report where someone else has reported the same problem. Microsoft have acknowledged this to be a bug in the framework, which will be resolved in the next version. In the meantime, I’m not aware of any straightforward workarounds other then having to specifically cater for the letter’s “f” and “g” in your code when doing any comparisons. That’s a bit crap Sad smile

Wednesday, July 27, 2011

A Tip For Writing Entity Framework Queries Using DateTime Values

Today I found a nice utility method for working with DateTime values in Entity Framework LINQ queries. I wanted a list of Events which fell between a date range, but my query needed to ignore the time portion of the DateTime values. My first attempt was this:

var events = this.coreDomainContext.Events.Where(
    e => e.EventDate.Value.Date >= DateTime.Today
      && e.EventDate.Value.Date <= endPeriod.Date)
    .OrderByDescending(e => e.EventDate)
    .ToList();

But when I ran the code, I got an exception because I was using the .Date property of DateTime - basically EF did not know what to do here to convert this into a query. So after some research I found EntityFunctions.TruncateTime. This worked like a charm:

var events = this.coreDomainContext.Events.Where(
    e => EntityFunctions.TruncateTime(e.EventDate.Value) >= DateTime.Today
      && EntityFunctions.TruncateTime(e.EventDate.Value) <= EntityFunctions.TruncateTime(endPeriod))
    .OrderByDescending(e => e.EventDate)
    .ToList();

EntityFunctions contains a ton of methods for working with EF entities, have a look through what’s on offer as it could save you from rolling your own EF hacks!

.NET DLL’s Duplicated In Memory–Update

A couple of years ago, I blogged about my findings after analysing the memory usage of RSS Bandit using VMMap. I found that numerous .NET assemblies were appearing twice in the virtual memory region of RSS Bandit and that this behaviour was a known issue to Microsoft. Well if you have a look at the Microsoft Connect page for this issue, you’ll spot that as of .NET 4.0 this issue has been resolved. I’m yet to perform any analysis myself on .NET 4.0 applications, to check if duplication of assemblies has been eradicated, but still, it’s nice to see that this has been resolved.

ASP NET MVC 3 Futures

If you're curious about some of the ideas that could come up in future versions of ASP NET MVC, then check this page. You will find examples of ideas such as:

- dynamic view pages.
- New ActionResults like AtomFeedActionResult.
- HTML helpers such as HTML.Button() and HTML.SubmitButton() (Finally :)

There is a ton of information available on that page, well worth a look.

Remember, there is a roadmap page for ASP NET MVC 4 which illustrates what the team are officially planning for the next release. If you would like to suggest a feature/improvement, then visit the ASP NET user voice page.

Thursday, February 17, 2011

The Death of .NET Reflector?

A few weeks ago, the software company Red Gate made the announcement that they will soon be ending the free availability of .NET Reflector. A summary of that can be found here. As you can imagine, many developers were unhappy at this decision. There were numerous calls of “traitors” and “liars” targeted towards the company, whom many thought had made a promise never to charge for .NET Reflector for editions other then the “Pro”. It is still in debate as to whether they actually did promise that, but’s that another story.

Not surprisingly, a few people have taken advantage of this situation. For example, a new tool named ILSpy has made an appearance. This is an open source project which is very early days, but could provide enough functionality for those looking for a lighter .NET assembly browser and decompiler – but most importantly, it’s free. By far the most heavy-weight competitor is Jetbrains who this evening gave details about their own .NET browser and decompiler. Their announcement can be found here. Their strategy is to include powerful .NET browsing and decompiling via their Resharper tool (version 6, which is currently in beta). Though the company have mentioned they intend to release a stand alone .NET assembly browser application in the future, which will be free. And they do mean “free”.

This leaves us with the question of just how are Red Gate going to get people to pay for .NET Reflector? What features could they implement which will make people think - “actually, I’m willing to pay £xx for that bit of functionality”. That’s a very good question. One cool feature in the Pro edition is the Visual Studio integration, where you can use .NET Reflector’s Visual Studio addin to debug compiled .NET framework assembly’s in the VS IDE. So if you wanted to know how String.IsNullOrEmpty worked, then you could step into that actual source code for that method. This is very cool, but as many will have spotted, the ability to debug .NET framework assemblies has been around for a few years now and is not difficult to setup, and is free.

I think .NET Reflector’s future is in trouble. To be fair, Red Gate’s reason to start charging is due to the resources required in order to maintain and build .NET Reflector. Anyone can understand that a company can’t just have a money-loosing product in their portfolio which offset by the profits made by other products. In the long term that does not make much sense. However, surely Red Gate is big enough to actually pull off that model? Else, why on earth would they want .NET Reflector in the first place? They knew it was free, they knew how much of a following it had. They knew how pissed off developers would be if they started charging for .NET Reflector. So why did they buy the rights to it….?

Friday, May 21, 2010

Wow! That’s A Lot Of Money

Apparently, Windows Vista cost Microsoft about $6 billion to develop. Check out the full article here.

Sunday, March 07, 2010

Another Long Wait

A while ago, I blogged about an Apress book on Apple Mac OS X that was due to be released in Aug 2020. Looks like there is another book on the way which we will have to wait with baited breath for:

image

Wow, only another 10 years to go before this badboy is unleashed on the public. Can’t wait. :)

Saturday, February 27, 2010

Good Blog Series On Using MSpec

Over on the Elegant Code blog there are some nice articles on MSpec which may be of interested to some of you. For those of you not familiar with MSpec, it’s a great open source BDD (Behaviour Driven Development) framework for .NET. Check it out.

Sunday, February 21, 2010

Time To Embrace The Cloud

You can’t help but notice the big increase in coverage for cloud computing both in IT news sites and developer blogs/forums. With the economic climate having been given a real beating the last couple of years, IT shops are looking into ways to reduce costs (hopefully by avoiding redundancies). Enter cloud computing. It’s a great idea and, frankly, one that is probably going to change the face of IT in the coming years.

As a developer, I accept that it’s only a matter of time before I will need to learn about developing for a cloud architecture. So rather then wait until that moment arrives, I’ve been doing a little bit of reading here and there about Windows Azure, Microsoft’s cloud offering which was made live a few weeks ago. I thought I’d post some links here to help out (both as notes for myself and to aid other people who might land on this blog).

Channel 9
Channel 9 - Cloud Cover Episode 1

PDC09 Videos
Lap Around The Windows Azure Platform
Development Best Practices and Patterns for Using Microsoft SQL Azure Databases
Scaling out Web Applications with Microsoft SQL Azure Databases
Patterns for Building Scalable and Reliable Applications with Windows Azure
Windows Azure Tables and Queues Deep Dive
Microsoft SQL Azure Database: Under the Hood
Windows Azure Present and Future
Windows Azure Blob and Drive Deep Dive
Windows Azure Monitoring, Logging, and Management APIs
Developing Advanced Applications with Windows Azure
Enabling Single Sign-On to Windows Azure Applications
Building Hybrid Cloud Applications with Windows Azure and the Service Bus
Lessons Learned: Migrating Applications to the Windows Azure Platform
Automating the Application Lifecycle with Windows Azure
The Future of Database Development with SQL Azure
Lessons Learned: Building On-Premises and Cloud Applications with the Service Bus and Windows Azure
Lessons Learned: Building Scalable Applications with the Windows Azure Platform
Lessons Learned: Building Multi-Tenant Applications with the Windows Azure Platform
Introduction to Building Applications with Windows Azure
SQL Azure Database: Present and Future
Tips and Tricks for Using Visual Studio 2010 to Build Applications that Run on Windows Azure
The Business of Windows Azure: What you should know about Windows Azure Platform pricing and SLAs

Misc
Windows Azure Tools for Microsoft Visual Studio 1.1 (February 2010)
Windows Azure Platform Training Kit - December Update
Migrating an Existing ASP.NET App to run on Windows Azure
Seven things that may surprise you about the Windows Azure Platform
OakLeaf Systems

Sunday, February 14, 2010

Nice BDD Naming Convention For MSTest

If you like to use Behaviour Driven Development (like me :) then I assume you are using a naming convention for your tests, maybe like this:

- Given an empty shopping cart
- When I add an item
- Then shopping item count should be 1

I really like using the above naming convention due to it expressiveness – I can instantly see what a test is actually testing and the context under which that test is running. I’ve been doing some research into the best practise for using BDD naming for MSTest unit tests and found this blog post. The author has given a very neat example of how to use a base context class which you can then include in your tests. The idea is that you have the following class which sets out the basic structure of a test:

using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace UnitTest
{
    public abstract class ContextSpecification
    {
        public TestContext TestContext { get; set; }

        [TestInitialize]
        public void TestInitialize()
        {
            Context();
            BecauseOf();
        }

        [TestCleanup]
        public void TestCleanup()
        {
            Cleanup();
        }

        protected virtual void Context()
        {
        }

        protected virtual void BecauseOf()
        {
        }

        protected virtual void Cleanup()
        {
        }
    }
}

Those of you who have used frameworks such as MSpec will find the above very familiar (I’m a big fan of MSpec and use it for some of my projects at work, but none of my colleagues us it, hence my need for finding an MSTest way of BDD’ing my unit tests). You have the usual MSTest related code (TestContext, TestInitialize, etc) declared in this class, but notice the Context, BecauseOf and Cleanup methods. We’ll take a look at how those are used now. Check out the following unit test:

namespace UnitTest
{
    public static class GetPersonNameSpecs
    {
        public class GetPersonNameSpecsContext : ContextSpecification
        {
            protected Person sut;
            protected string actual = String.Empty;
        }

        [TestClass]
        public class when_name_has_not_been_given : GetPersonNameSpecsContext
        {
            protected override void Context()
            {
                sut = new Person();
            }

            protected override void BecauseOf()
            {
                actual = sut.GetFullName();
            }

            [TestMethod]
            public void returned_name_should_be_empty()
            {
                Assert.AreEqual(String.Empty, actual);
            }
        }

        [TestClass]
        public class when_name_has_been_given : GetPersonNameSpecsContext
        {
            protected override void Context()
            {
                sut = new Person("Jim");
            }

            protected override void BecauseOf()
            {
                actual = sut.GetFullName();
            }

            [TestMethod]
            public void returned_name_should_be_Jim()
            {
                Assert.AreEqual("Jim", actual);
            }
        }
    }
}

As per the suggestion of the blog author, I have a static class named GetPersonNameSpecs and inside that class is the real meat and bones – two test classes which contain the unit tests. See how I make use of the Context and BecauseOf methods - with Context I can do my pre-test initialisation (creating class instances, or if I was using a mock framework, creating mock objects), then in the BecauseOf method I invoke the code to be tested. The final phase of the test, the assertion, is what’s declared with a [TestMethod] attribute. Since in ContextSpecification both Context and BecauseOf are called during TestInitialize, there is no need for us to apply any attributes to our version of those methods.

The advantage of this structure is it’s readability, take a look at how the above tests look like in my test viewer window:

image

and in the results window:

image

Now, I don’t know about you, but I know that if I had to return to these tests in 6 months time, I will find it much easier to deal with.