MSTest/NUnit Writing BDD style "Given, When, Then" tests

Posted by Charlie on Stack Overflow See other posts from Stack Overflow or by Charlie
Published on 2011-01-13T10:13:54Z Indexed on 2011/01/13 10:53 UTC
Read the original article Hit count: 275

Filed under:
|
|
|
|

I have been using MSpec to write my unit tests and really prefer the BDD style, I think it's a lot more readable. I'm now using Silverlight which MSpec doesn't support so I'm having to use MSTest but would still like to maintain a BDD style so am trying to work out a way to do this.

Just to explain what I'm trying to acheive, here's how I'd write an MSpec test

[Subject(typeof(Calculator))]    
public class when_I_add_two_numbers : with_calculator
{
  Establish context = () => this.Calculator = new Calculator();
  Because I_add_2_and_4 = () => this.Calculator.Add(2).Add(4);
  It should_display_6 = () => this.Calculator.Result.ShouldEqual(6);
}

public class with_calculator
{
  protected static Calculator;
}

So with MSTest I would try to write the test like this (although you can see it won't work because I've put in 2 TestInitialize attributes, but you get what I'm trying to do..)

[TestClass]
public class when_I_add_two_numbers : with_calculator
{
   [TestInitialize]
   public void GivenIHaveACalculator()
   {
      this.Calculator = new Calculator();
   }

   [TestInitialize]
   public void WhenIAdd2And4()
   {
      this.Calculator.Add(2).Add(4);
   }

   [TestMethod]
   public void ThenItShouldDisplay6()
   {
      this.Calculator.Result.ShouldEqual(6);
   }
}

public class with_calculator
{
  protected Calculator Calculator {get;set;}
}

Can anyone come up with some more elegant suggestions to write tests in this way with MSTest? Thanks

© Stack Overflow or respective owner

Related posts about c#

Related posts about unit-testing