Kash Farooq's software development blog

.NET Developer

More TDD with wrapper classes

Posted by Kash Farooq on June 23, 2012

I have previously blogged about using wrapper classes to test the hard to test. In that post I made things easy for myself by using the parameterless constructor of the SmtpClient class.

I thought I’d revisit this area of testing, and try something different. This time I’ve used Moq rather than Rhino Mocks for starters. But I’m also going to pretend that SmtpClient does not have a parameterless constructor.  If a class you need to make testable does not have a parameterless constructor, it makes things a bit trickier:

public class SystemUnderTest
{
  public void MethodToBeTested()
  {
    var mailMessage = new MailMessage { Subject = "Hello", From = new MailAddress("Me@Me.com") };
    mailMessage.To.Add(new MailAddress("You@You.com"));
    var smtpClient = new SmtpClient("smtp.kashfarooq.com", 25);
    smtpClient.Send(mailMessage);
  }
}

A number of things in the above code need to be addressed and tested. The SMTP client is being instantiated in the method with the host and port being sent in via a the constructor, which makes things awkward to test. Apart from that complication, I’d like to make sure the correct host and port are being used. And I’d also like to make sure the correct details are being set in the MailMessage object.

First, we need an interface so we can mock the Send method. This matches the SmtpClient.Send method exactly:

public interface ISmtpClient
{
  void Send(MailMessage mailMessage);
}

We also need a wrapper class that will wrap SmtpClient and the constructor we are planning to use:

public class SmtpClientWrapper : SmtpClient, ISmtpClient
{
  public SmtpClientWrapper(string host, int port) : base(host, port)  { }
}

The above wrapper class inherits the interface defined above and the class we are trying to make testable: SmtpClient. And as it derives from SmtpClient, it automatically implements ISmtpClient.Send(MailMessage).

Next, we’ll create a suitable constructor for our SystemUnderTest class so that we can inject in some mocks. Because the MethodToBeTested creates the SmtpClient object, I’m going to use the “Using a Func instead of a Factory” trick:

private readonly Func<string, int, ISmtpClient> createSmtpClient;

public SystemUnderTest(Func<string, int, ISmtpClient> createSmtpClient)
{
  this.createSmtpClient = createSmtpClient;
}

public SystemUnderTest() : this((host,port) => new SmtpClientWrapper(host, port)) {}

So, what’s going on here? I have created a Func that will take a string and int (the host and port) and return an ISmtpClient. From my test I’ll use the first constructor. The production code will use the second constructor. In both cases, the Func supplied is stored in createSmtpClient – and this will be called from MethodToBeTested to actually create the SmtpClient.

I’m now in full control of all the dependencies. I can catch the MailMessage parameter sent to the Send method, and the host and port name sent to the createSmtpClient Func, which ultimately gets sent to to the SmtpClient(string host, int port) constructor.

And here is the test that creates a mock ISmtpClient and a Func that returns it, and also catches the parameters sent to it so the appropriate asserts can be done:

[Test]
public void CorrectEmailSentViaTheCorrectSmtpHost()
{
  string actualHostName=string.Empty;
  int actualPort=0;
  MailMessage actualMailMessage = null;

  var mockSmtpClient = new Mock<ISmtpClient>();
  mockSmtpClient
     .Setup(x => x.Send(It.IsAny<MailMessage>()))
     .Callback((MailMessage message) => actualMailMessage = message); //Catch the MailMessage sent to the Send method

  //Func to return an ISmtpClient and catch data sent to it
  Func<string, int, ISmtpClient> createSmtpClient = (host, port) =>
      {
         actualHostName = host; //catch the hostname used
         actualPort = port; //catch the port used
         return mockSmtpClient.Object; //return mocked SmtpClient
  };

  //Call system under test
  var sut = new SystemUnderTest(createSmtpClient);
  sut.MethodToBeTested();

  //Asserts
  actualHostName.Should().Be("smtp.kashfarooq.com");
  actualPort.Should().Be(25);
  actualMailMessage.Subject.Should().Be("Hello");
  actualMailMessage.From.Address.Should().Be("Me@Me.com");
  actualMailMessage.To[0].Address.Should().Be("You@You.com");
}

[Incidentally, I’m using the excellent FluentAssertions in my asserts.]

Posted in .NET, Moq, Test Driven Development | Tagged: , , , | Leave a Comment »

How to test DateTime.Now

Posted by Kash Farooq on June 17, 2012

A colleague new to TDD asked me how to do this recently, so I thought I’d blog it.

Here is some code we want to bring under test:

public void SomeMethodToBeTested()
{
  var dateTimeNow = DateTime.Now;
  if (dateTimeNow.Month == 4 && dateTimeNow.Day == 6)
  {
    //do something for the new tax year.
  }
  else
  {
    //do something for the current tax year.
  }
}

The problem is: how can we test different dates so make sure the correct tax year dependent processing takes place? We clearly need the ability to control the date being used. We could do this by creating a wrapper class for DateTime, but I prefer in this simple case to just use a Func.

The test code becomes:

[TestFixture]
public class StubbingDateTimeNowTest
{
  [Test]
  public void TestNewTaxTear()
  {
    var stubbingDateTimeNow=new StubbingDateTimeNow(() => new DateTime(2012,4,6)); //send in a Func to return the date I want to test
    stubbingDateTimeNow.SomeMethodNowTested();
    //Asserts to check correct processing took place
  }

  [Test]
  public void TestCurrentTaxTear()
  {
    var stubbingDateTimeNow=new StubbingDateTimeNow(() => new DateTime(2012,3,6)); //send in a Func to return the date I want to test
    stubbingDateTimeNow.SomeMethodNowTested();
    //Asserts to check correct processing took place
  }
}

And the code under test needs a constructor to enable me to inject in the Func that creates a DateTime object. The default constructor that would be called in production simply provides a Func that will return DateTime.Now when called:

public class StubbingDateTimeNow
{
  private readonly Func<DateTime> getCurrentDateTime;

  public StubbingDateTimeNow(Func<DateTime> getCurrentDateTime)
  {
    this.getCurrentDateTime = getCurrentDateTime;
  }

  public StubbingDateTimeNow() : this(() => DateTime.Now) {} //default constructor provides a Func to return DateTime.Now

  public void SomeMethodNowTested()
  {
     var dateTimeNow = getCurrentDateTime();
     if (dateTimeNow.Month == 4 && dateTimeNow.Day == 6)
     {
       //do something for the new tax year.
     }
     else
     {
       //do something for the current tax year.
     }
  }
}

Posted in .NET, Test Driven Development | Tagged: , , | Leave a Comment »

Cloning an Object

Posted by Kash Farooq on June 15, 2012

I thought I’d post this code as I frequently find myself needing it on various projects.

Making a deep copy clone of an object:

public static T CloneObject<T>(T objectToClone) {
  using (var memoryStream = new MemoryStream()) {
    var xmlSerializer = new XmlSerializer(typeof (T));
    xmlSerializer.Serialize(memoryStream, objectToClone);
    memoryStream.Position = 0;
    return (T) xmlSerializer.Deserialize(memoryStream);
  }
}

Basically, serialize an object to memory and then deserialize it into a completely different new object, breaking the memory reference.

Posted in .NET | Tagged: , , | Leave a Comment »

MongoDB in C#: Mapping IDs

Posted by Kash Farooq on March 4, 2012

In my previous post about C# and MongoDB, I polluted my domain model with a MongoDB type:

public class Movie
{
  public BsonObjectId Id { get; set; }
  public string Title { get; set; }
  public string Year { get; set; }

  etc
}

When you Insert a document into MongoDB using the C# driver, the driver needs to check to see if the Id has a value. It assigns one if it doesn’t. The above code worked because I used a MongoDB C# driver ID type – the driver could work out what my ID property is. But I don’t really want to use BsonObjectId in this class – it ties me to MongoDB. Instead, you can use a built-in .NET type for the ID property and tell the MongoDB C# driver about it.

First, let’s change the type of the Id property. I’ve gone for a string but there are other types you could use:

public class Movie
{
  public string Id { get; set; }
  public string Title { get; set; }
  public string Year { get; set; }

  etc
}

Now, you need to map that property. I’m doing this code in an NUnit test, so I’m going to do the mapping in the TestFixtureSetUp:

[TestFixtureSetUp]
public void TestFixtureSetUp()
{
  BsonClassMap.RegisterClassMap<Movie>(cm => {
                                              cm.AutoMap();
                                              cm.SetIdMember(cm.GetMemberMap(x => x.Id).SetIdGenerator(StringObjectIdGenerator.Instance));
                                             }
                                       );
}

So, I’ve told the MongoDB C# driver that the ID column is Movie.Id and that it needs to use its built in StringObjectIdGenerator to generate IDs.

There are several ID generators built into the driver:

  • BsonObjectIdGenerator
  • CombGuidGenerator
  • GuidGenerator
  • NullIdChecker
  • ObjectIdGenerator
  • StringObjectIdGenerator
  • ZeroIdChecker<T>

Read the CSharp Driver Serialization Tutorial for more information about these generators and mapping them to properties.

Posted in .NET, NoSQL | Tagged: , , , | Leave a Comment »

Cleaning all bin and obj files with MSBuild

Posted by Kash Farooq on February 26, 2012

I thought I’d blog this as it took me a frustratingly long time to work out how to do it (I’m new to MSBuild scripts – I usually do my builds with nant).

I wanted to simply clean my solution before the build. The solutions I found on Stack Overflow were unsatisfactory. For example, I didn’t want to have to name the folders that I wanted to delete files from.

So, here’s what I did; I simply called the “Clean” MSBuild target for all csproj files found below the directory the build was initiated from:


<?xml version="1.0" encoding="utf-8" ?>
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003" DefaultTargets="Build-and-test">

  <Target Name="Build-and-test">
    <CallTarget Targets="clean-all-folders"/>
    <CallTarget Targets="build"/>
    <CallTarget Targets="unit-tests"/>
  </Target>

  <ItemGroup>
    <ProjectFiles Include="**\*.csproj" />
  </ItemGroup>

  <Target Name="clean-all-folders">
    <MSBuild Projects="@(ProjectFiles)" targets="Clean" />
  </Target>

  etc.
</Project>

This doesn’t delete the bin, debug and obj folders – but I don’t believe that is a problem.

The above script is generic – it doesn’t care what the project files or solution are called.

You can eliminate the ItemGroup if you are willing to hard code your solution file:

<Target Name="clean-all-folders">
   <MSBuild Projects="MySolition.sln" targets="Clean" />
</Target><

Posted in .NET, Continuous Integration | Tagged: , | Leave a Comment »

Playing with FluentAssertions

Posted by Kash Farooq on February 23, 2012

I thought I’d try a FluentAssertions – a different way of doing asserts in Unit Tests.

As the name of the library suggests, your assertion code is fluent. i.e. methods are chained.

Some examples.

A simple assert:

person.YearOfBirth.Should().Be(1945);

To check a list has the correct number of elements:

personList.Should().HaveCount(10);

To ensure that a list has elements in a certain order:

IEnumerable<int> positions = personList.Select(x => x.Rank);
positions.Should().ContainInOrder(new[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10});

There are lots of helper methods and the lots of examples in the on-line documentation.

I quite like it and have been using it on a project.

And it’s not just the assertion style that I like.

The thing that really impressed me was when one of my tests failed. In my assert I was comparing two strings. I clearly should have done a .Trim() on my string under test, but I forgot. And here is the error I saw in my test runner window:


Expected string to be
"John Smith", but it has unexpected whitespace at the end.

How useful is that! No more “the string differs at position 45”.

Posted in .NET, Test Driven Development | Tagged: , , | Leave a Comment »

Getting started with MongoDB in C#

Posted by Kash Farooq on February 18, 2012

I thought I’d play with NoSQL. There are lots of implementations to choose from, but I’ve decided to start with MongoDB. Especially after seeing the impressive list of real-life production MongoDB deployments.

The MongoDB server and data structure is organised as follows:

  • A Mongo server holds a set of databases
  • A database holds a set of collections
  • A collection holds a set of documents
  • A document is a set of fields
  • A field is a key-value pair
  • A key is a string
  • A value is a
    • strings, integers, etc.
    • another document
    • an array of values

Right. Let’s get started. First, download the two things you’ll need to start developing MongoDB apps in .NET: the database software and the C# driver.

I also recommend you download a PDF of the documentation. It is available as a MongoDB docs daily build. This PDF contains everything: set-up instructions, tutorials, advice and language specific driver documentations.

Use the Windows Quick Start to get going and test your MongoDB server with the administrative JavaScript shell client. I also advise you go through the tutorial – it walks you through more complex examples using the administrative shell client. As noted above, both these guides are in the MongoDB Docs PDF.

Install the C# driver by just running the MSI. It installs to C:\Program Files (x86)\MongoDB.

Create a .NET project and add assembly references to MongoDB.Driver.dll and MongoDB.Bson.dll. I created NUnit integration tests to test MongoDB.

First, I created a class that I wanted to store as a MongoDB document:

public class Movie
{
  public BsonObjectId Id { get; set; }
  public string Title { get; set; }
  public string Year { get; set; }
  public List<string> Actors { get; set; }

  public void AddActor(string actor)
  {
    if (Actors == null)
    {
      Actors = new List<string>();
    }
    Actors.Add(actor);
  }
}

Things to note in this class:

  • I’ve used the type BsonObjectId. To get up and running quickly, I basically told the MongoDB C# driver which property to use as an ID. You don’t have to do this. To see how to remove MongoDB C# driver specific types from your domain object, see my Mapping IDs post.
  • I’ve included a generic list – I wanted to see how the C# driver copes with this, how MongoDB stores this data, and how we can search for documents using this data.
  • I had to make the Actors list public, otherwise the C# driver wouldn’t store it. Perhaps there is a way to force the driver to store it without making it public? Something to research.

Next, let’s open a connection to a database and insert some data. I’m orchestrating the prerequisites for my test through a NUnit Setup method the connects to the database, empties the collection and inserts some fresh data:

private MongoServer server;
private MongoDatabase moviesDatabase;

[SetUp]
public void SetUp()
{
  Connect();
  Clean();
  InsertData();
}

private void Connect()
{
  server = MongoServer.Create();
  moviesDatabase = server.GetDatabase("movies_db");
}

As you can see, the connect method didn’t use any information such as connection strings, usernames, etc. It just calls Create. If you don’t provide any parameters it connects to a default instance of MongoDB on localhost. If you’ve changed any of the default settings, you’ll need a connection string.

The GetDatabase method gets me an instance of the “movies” database if it exists, or lazily creates it if it doesn’t (i.e. it won’t actually be created until you save some data to it).

The Clean() method is just used to empty the collection each time a test runs. I’m calling the RemoveAll method to empty all elements from the movies_collection:

private void Clean()
{
  var moviesCollection = moviesDatabase.GetCollection<Movie>("movies_collection");
  moviesCollection.RemoveAll();
}

Now let’s add some data to the movies_collection and save it to the movies_db:

private void InsertData()
{
  //Create some data
  var movie1 = new Movie {Title = "Indiana Jones and the Raiders of the Lost Ark", Year = "1981"};
  movie1.AddActor("Harrison Ford");
  movie1.AddActor("Karen Allen");
  movie1.AddActor("Paul Freeman");

  var movie2 = new Movie {Title = "Star Wars: Episode IV - A New Hope", Year = "1977"};
  movie2.AddActor("Mark Hamill");
  movie2.AddActor("Harrison Ford");
  movie2.AddActor("Carrie Fisher");

  var movie3 = new Movie {Title = "Das Boot", Year = "1981"};
  movie3.AddActor("Jürgen Prochnow");
  movie3.AddActor("Herbert Grönemeyer");
  movie3.AddActor("Klaus Wennemann");

  //Insert the movies into the movies_collection
  var moviesCollection = moviesDatabase.GetCollection<Movie>("movies_collection");
  moviesCollection.Insert(movie1);
  moviesCollection.Insert(movie2);
  moviesCollection.Insert(movie3);
}

So, we’ve created/opened a database called movie_db and insert some data into a movies_collection. Let’s check it’s there – get the collection and check that there are 3 movies in it.

[Test]
public void ShouldFindThreeMoviesInTheCollection()
{
  var moviesCollectionRetrieved = moviesDatabase.GetCollection<Movie>("movies_collection");
  Assert.That(moviesCollectionRetrieved.Count(), Is.EqualTo(3));
}

Now let’s do a query on the movie data. Let’s look for movies that were released in 1981, i.e. perform a query based on one of the keys – in this case, the “Year” key:

[Test]
public void ShouldFindTwoMoviesThatWereMadeIn1981()
{
  var moviesCollectionRetrieved = moviesDatabase.GetCollection<Movie>("movies_collection");

  QueryComplete findMoviesMadeIn1981Query = Query.EQ("Year", "1981");
  var moviesFound = moviesCollectionRetrieved.FindAs<Movie>(findMoviesMadeIn1981Query);

  Assert.That(moviesFound.Count(), Is.EqualTo(2));
  Assert.That(moviesFound.Count(movie => movie.Title == "Das Boot"), Is.EqualTo(1));
  Assert.That(moviesFound.Count(movie => movie.Title == "Indiana Jones and the Raiders of the Lost Ark"),Is.EqualTo(1));
}

Note that I used the generic version FindAs method – to get the C# driver to create movie objects from the MongoDB documents.

You can also very easily perform queries based on values stored in lists. Here, for example, I am looking for documents that contain a certain value in the Actors list – let’s look for movies that Harrison Ford has been in:

[Test]
public void ShouldFindTwoMoviesThatHarrisonFordHasBeenIn()
{
  var moviesCollectionRetrieved = moviesDatabase.GetCollection<Movie>("movies_collection");

  var findMoviesWithHarrisonFordInThem = Query.EQ("Actors", "Harrison Ford");
  var moviesFound = moviesCollectionRetrieved.FindAs<Movie>(findMoviesWithHarrisonFordInThem);
  Assert.That(moviesFound.Count(), Is.EqualTo(2));
  Assert.That(moviesFound.Count(movie => movie.Title == "Star Wars: Episode IV - A New Hope"),Is.EqualTo(1));
  Assert.That(moviesFound.Count(movie => movie.Title == "Indiana Jones and the Raiders of the Lost Ark"),Is.EqualTo(1));
}

Very neat.

In the code above I’ve been using Count(). That does not mean that the C# driver supports delayed execution and LINQ. The official statement is: “Version 1.0 of the official C# driver does not yet support LINQ”. In fact, the documentation states that for the following code, the query is sent to the server twice (once for FirstOrDefault and once for LastOrDefault)


var query = Query.EQ("author", "Ernest Hemingway");
var cursor = books.Find(query);
var firstBook = cursor.FirstOrDefault(); //query executed twice on the server
var lastBook = cursor.LastOrDefault(); //once for each of these IEnumerable<T> extension methods.

Finally, let’s look at how the data has been stored using the administrative JavaScript shell client, mongo.exe.

With the client, I’ll connect to the server, switch to the movies database and then display all the documents in the movies_collection:


MongoDB shell version: 2.0.2
connecting to: test
> use movies_db
switched to db movies_db
> db.movies_collection.find().forEach(printjson);
{
 "_id" : ObjectId("4f3f82a1d5c8851b60430b9a"),
 "Title" : "Indiana Jones and the Raiders of the Lost Ark",
 "Year" : "1981",
 "Actors" : [
 "Harrison Ford",
 "Karen Allen",
 "Paul Freeman"
 ]
}
{
 "_id" : ObjectId("4f3f82a1d5c8851b60430b9b"),
 "Title" : "Star Wars: Episode IV - A New Hope",
 "Year" : "1977",
 "Actors" : [
 "Mark Hamill",
 "Harrison Ford",
 "Carrie Fisher"
 ]
}
{
 "_id" : ObjectId("4f3f82a1d5c8851b60430b9c"),
 "Title" : "Das Boot",
 "Year" : "1981",
 "Actors" : [
 "J├╝rgen Prochnow",
 "Herbert Gr├Ânemeyer",
 "Klaus Wennemann"
 ]
}
>

Posted in .NET, NoSQL | Tagged: , , , | Leave a Comment »

BDD with SpecFlow and Coypu (Part 2)

Posted by Kash Farooq on August 23, 2011

In my last post I introduced BDD with SpecFlow. I created a  feature file and got to a point where I now needed to hook up my BDD tests with browser integration. To do this, I’m going to use Coypu and the Selenium headless browser. See my previous post for download links.

First, let’s configure Coypu to use the Selenium headless browser:

[Binding]
public class CoypuInitializer {
    [BeforeTestRun]
    public static void BeforeTestRun()
    {
        //I'm using the Dev Studio cassini server;
        Configuration.AppHost = "localhost";
        Configuration.Port = 64567;

        ConfigureForHeadlessBrowser();
    }

    private static void ConfigureForHeadlessBrowser()
    {
        Configuration.Driver = typeof(SeleniumHtmlUnitWebDriver);
    }

    [AfterScenario]
    public static void AfterScenario()
    {
        Coypu.Browser.EndSession();
    }
}

 

public class SeleniumHtmlUnitWebDriver : SeleniumWebDriver {
    public SeleniumHtmlUnitWebDriver() : base(new RemoteWebDriver(DesiredCapabilities.HtmlUnit())) {}
}

You will also need to add DLL references to Coypu.dll and WebDriver.dll (which is in the Coypu zip).

You can use this class to make other global configuration settings such as the Timeout, or the time Coypu waits between retries when looking for a HTML element. Full details can be found at the GitHub Coypu website, or the README.md file that comes with the Coypu binaries.

Now we are ready to implement the first feature step. As a reminder, the feature file is:

Scenario: Display Pi using Taylor series and Bucknall's BigNumber to many decimal places
	Given I visit the Pi.NET website
	And I have selected the 'Bucknall Big Number' algorithm
	And I have entered 500 decimal places
	When I press Go
	Then Pi should be displayed to the correct number of decimal places
	And Calculation statistics should be displayed

Let’s implement the “Given I visit the Pi.NET website” step:

[Given(@"I visit the Pi\.NET website")]
public void GivenIVisitThePiWebsite() {
    Browser.Session.Visit(string.Format("/"));
}

Using Coypu, I’m going to open the website specified in the CoypuInitializer class and visit the root of that website.

I now go to my MVC app and implement just enough to get that step passing.

Once I’ve done that, running the tests now gives:


Given I visit the Pi.NET website
-> done: PiNetSteps.GivenIVisitThePiWebsite() (15.4s)
And I have selected the 'Bucknall Big Number' algorithm
-> pending: PiNetSteps.GivenIHaveSelectedTheBucknallBigNumberAlgorithm("Bucknall Big Number")

i.e. – the first step has completed and the test has stopped at the next pending step. We’ve successfully hit the website.

I proceed like this, step by step, until I end up with the following steps file. I’ve added comments to explain the Coypu features I am using:

[Binding]
public class PiNetSteps:Steps {
    private string numberOfDecimalPlaces;

    [Given(@"I have selected the '(.+)' algorithm")]
    public void GivenIHaveSelectedAnAlgorithm(string algorithm) {
        //pass on this call to the generic radio button method (later in this class)
        Given(string.Format("I select the radio button '{0}'", algorithm));
    }

    [Given(@"I have entered (.+) decimal places")]
    public void GivenIHaveEnteredTheNumberOfRequiredDecimalPlaces(string numberOfDecimalPlaces) {
        this.numberOfDecimalPlaces = numberOfDecimalPlaces; //store for later use in an assert
        //populate a text box
        Browser.Session.FillIn("NumberOfDecimalPlaces").With(numberOfDecimalPlaces);
    }

    [When(@"I press Go")]
    public void WhenIPressGo() {
        //click a link. This fires an AJAX post to controller action
        //(I wanted to test JS capabilities of Selenium headless browser)
        Browser.Session.ClickLink("Calculate");
    }

    [Then(@"Pi should be displayed to the correct number of decimal places")]
    public void ThenPiShouldBeDisplayedToTheRequestedNumberOfDecimalPlaces() {
        //Check page HasContent I'm after - "Number of iterations" is displayed by AJAX call result
        if (Browser.Session.HasContent("Number of iterations:")) {
            //check Pi is calculated to correct number of places
            string piToNumberOfRequiredDecimalPlaces = Pi.Get(Convert.ToInt32(numberOfDecimalPlaces));
            Element piElement = Browser.Session.FindField("pi"); //find HTML element
            string calculatedPi = piElement.Text;
            Assert.That(piToNumberOfRequiredDecimalPlaces, Is.EqualTo(calculatedPi));
        }
        else {
            Assert.Fail("Could not find PI");
        }
    }

    [Then(@"Calculation statistics should be displayed")]
    public void ThenCalculationStatisticsShouldBeDisplayed() {
        //you can use actions/funcs with different retry timeouts
        Assert.IsTrue(Browser.Session.WithIndividualTimeout(TimeSpan.FromMilliseconds(1),
                       () => Browser.Session.HasContent("Number of iterations: ")),
                       "Number of Iterations taken not found");
        Assert.IsTrue(Browser.Session.WithIndividualTimeout(TimeSpan.FromMilliseconds(1),
                       () => Browser.Session.HasContent("Number of decimal places: " + numberOfDecimalPlaces)),
                       "Number of Decimal places calculated not found");
        Assert.IsTrue(Browser.Session.WithIndividualTimeout(TimeSpan.FromMilliseconds(1),
                       () => Browser.Session.HasContent("Elapsed Milliseconds: ")),
                       "Time taken not found");
    }

    [Given(@"I select the radio button '(.+)'")]
    public void SelectARadioButton(string radioButtonValue) {
        //select a radio button by value
        Browser.Session.Choose(radioButtonValue);
    }

    [Given(@"I visit the Pi.NET website")]
    public void GivenIVisitThePiPage() {
        //visit a web page at site specified in Coypu initialization.
        Browser.Session.Visit(string.Format("/"));
    }
}

I’ve used several SpecFlow and Coypu features in the class above. There are many more that you can read about at the GitHub Coypu website, or the README.md file that comes with the Coypu binaries. The documentation also shows how to use a real browser, rather than the Selenium headless one.

Posted in .NET, Behaviour Driven Development, Test Driven Development | Tagged: , , , , | Leave a Comment »

BDD with SpecFlow and Coypu (Part 1)

Posted by Kash Farooq on August 19, 2011

I’ve been doing TDD for years and I thought it was about time I got into BDD too.

I’m going to use BDD to add a UI in front of the various implementations of Pi calculation algorithms I’ve been working on.

This post will describe what you need to install and how to get a SpecFlow feature file running via NUnit.

Prerequisites

Headless browser:

Firing up a real browser from a BDD test can be slow. So, I’m using the Selenium headless Java browser.

Download selenium-server-standalone-2.4.0.jar (and, of course, you need Java)

To start it up:


java -jar selenium-server-standalone-2.3.0.jar

SpecFlow:

Install SpecFlow with the full installer and it will integrate with Dev Studio.

You can keep your feature files in your solution and SpecFlow will automatically generate NUnit based code-behind files.

I also recommend you watch the SpecFlow Screen Cast – an excellent introduction to quickly get you up and running.

Coypu

To get my SpecFlow BDD tests to interact with the browser, I’m using Coypu.

Coypu is:

A more intuitive DSL for interacting with the browser in the way a human being would, inspired by the ruby framework Capybara.

Other software

You need NUnit (as SpecFlow creates NUnit tests).

Adding the first feature file

I’ve already got a few implementations of algorithms to calculate Pi. I just want a simple UI that allows you to select an algorithm, type how many decimal places you want Pi calculated to, and then hit “Calculate”. I want the “Calculate” link/button to call back to my application via AJAX (I want to see how the headless browser copes with Javascript).

Step 1: Add a feature file

A feature file is just a text file that describes the functionality you want to implement. It has a simple Given-When-Then structure that should be understandable by non-developers. Hence, they could be created by Business Analysts, etc.

I created a new class library called Spec and added a feature file using the “Add New Item” Dev Studio menu. You’ll see the option “SpecFlow Feature File”.

Feature: Calculate Pi using various algorithms
	I want to be able to view Pi to varying decimal places

Scenario: Display Pi using Taylor series and Bucknall's BigNumber to many decimal places
	Given I visit the Pi.NET website
	And I have selected the 'Bucknall Big Number' algorithm
	And I have entered 500 decimal places
	When I press Go
	Then Pi should be displayed to the correct number of decimal places
	And Calculation statistics should be displayed

You’ll also need to add DLL references to TechTalk.SpecFlow.dll and nunit.framework.dll

Once you’ve done this, compile and run all the unit tests in your Spec class library. You’ll see output like this:


Given I visit the Pi.NET website
-> No matching step definition found for the step. Use the following code to create one:
[Binding]
public class StepDefinitions {
   [Given(@"I visit the Pi\.NET website")]
   public void GivenIVisitThePi_NETWebsite()
   {
       ScenarioContext.Current.Pending();
   }
}
etc, etc.

SpecFlow has told you exactly what you need to do.

So, let’s copy and paste the code into a new C# file called PiNetSteps:

[Binding]
public class PiNetSteps {
    [Given(@"I visit the Pi\.NET website")]
    public void GivenIVisitThePi_NETWebsite() {
        ScenarioContext.Current.Pending();
    }

    [Given(@"I have selected the 'Bucknall Big Number' algorithm")]
    public void GivenIHaveSelectedTheBucknallBigNumberAlgorithm() {
        ScenarioContext.Current.Pending();
    }

    [Given(@"I have entered 500 decimal places")]
    public void GivenIHaveEntered500DecimalPlaces() {
        ScenarioContext.Current.Pending();
    }

    [When(@"I press Go")]
    public void WhenIPressGo() {
        ScenarioContext.Current.Pending();
    }

    [Then(@"Pi should be displayed to the correct number of decimal places")]
    public void ThenPiShouldBeDisplayedToTheCorrectNumberOfDecimalPlaces() {
        ScenarioContext.Current.Pending();
    }

    [Then(@"Calculation statistics should be displayed")]
    public void ThenCalculationStatisticsShouldBeDisplayed() {
        ScenarioContext.Current.Pending();
    }
}

Now when you run the unit tests you get the output:


Ignored: One or more step definitions are not implemented yet.

We can improve the steps code by parameterizing it with Regex. For example, rather than hard coding “500 decimal places”, let’s make this a parameter. And the algorithm name can also be a parameter.

Making these changes gives:

[Given(@"I have selected the '(.+)' algorithm")]
public void GivenIHaveSelectedAnAlgorithm(string algorithm) {
    ScenarioContext.Current.Pending();
}

[Given(@"I have entered '(.+)' decimal places")]
public void GivenIHaveEnteredTheRequiredNumberOfDecimalPlaces(int numberOfDecimalPlaces) {
    this.numberOfDecimalPlaces = numberOfDecimalPlaces; //store for a later assert
    ScenarioContext.Current.Pending();
}

We’re now at a stage that opens up lots of possibilities. You’ve gone from a feature file to a C# class and you now have options on how deep you want your tests to go. If you system under test is not a web application, you are ready to start implementing it straight away. If your system has lots of external dependencies that are not under your control, you could easily stub them out with a container. Or perhaps you want your tests to go through all the application layers and hit a database or webservice. You could easily introduce test database and webservices if you wish.

In the next post I’ll get Coypu up and running and use it to get my SpecFlow steps class to hit the Selenium headless browser.

Next: BDD with SpecFlow and Coypu (Part 2)

Posted in .NET, Behaviour Driven Development, Test Driven Development | Tagged: , , , | Leave a Comment »

Calculating Pi in C# part 3 – using the BigRational class

Posted by Kash Farooq on August 1, 2011

In an earlier post I ported a Java implementation of a Pi calculator – my port used the BigInteger class that lives in the System.Numerics assembly of .NET 4. I also performance tested my port against an implementation by Julian M Bucknall that used his own BigNumber class. Julian’s implementation won that performance test, coming in at an impressive 70-80 milliseconds to calculate Pi to 1000 decimal places.

Now it is time for me to try an implementation alone!

I’m going to use the following John Machin formula:

John Machin's Pi formulaArctan can be calculated using the following Taylor series:

ArcTan calculated using the Taylor SeriesRather than creating arbitrarily big numbers with BigInteger, I need to create numbers with arbitrarily large precision.   I need a BigRational. And one exists, but it did not make it into the .NET 4 framework. You can download BigRational form CodePlex.

So, here is my implementation of arctan:

public class ArcTanWithBigRational {
    public ArcTanWithBigRational() {
        Iterations = 0;
    }

    public int Iterations;

    public BigRational Calculate(BigRational x, int maxNumberOfIterations, int precision) {
        bool doASubtract = true;
        BigRational runningTotal = x;
        int count = 0;
        var divisor = new BigInteger(3);
        while (count < maxNumberOfIterations) {
            BigRational current = BigRational.Pow(x, divisor);
            current = current/divisor;
            if (doASubtract) {
                runningTotal = runningTotal - current;
            }
            else {
                runningTotal = runningTotal + current;
            }
            doASubtract = !doASubtract;
            count++;
            divisor = divisor + 2;
            if (WeHaveEnoughPrecision(current, precision)) {
                Iterations = count;
                break;
            }
        }
        return runningTotal;
    }

    private static bool WeHaveEnoughPrecision(BigRational current, int precision) {
        return current.GetFractionPart().ToString().Length > precision+2; //extra 2 digits to ensure enough precision
    }
}

Now to perform the calculation:

public string Calculate(int numberOfDigits) {
    var arcTanA = new ArcTanWithBigRational();
    var arcTanB = new ArcTanWithBigRational();
    var a = 16 * arcTanA.Calculate(BigRational.Divide(1, 5), 1000, numberOfDigits);
    var b = 4 * arcTanB.Calculate(BigRational.Divide(1, 239), 1000, numberOfDigits);
    var pi = a - b;
    return BigRationalPiFormatter.Format(pi, numberOfDigits);
}

And the results:

Precision = 1000 digits
Number of iterations = 923
Elapsed Milliseconds = 1192

Not bad! No where near as fast as the other implementations in my previous post, but not too bad and with far fewer iterations.

I can try one final optimization to try and get my implementation running faster. I have a dual-core laptop so let’s try some Parallel Tasks:

public string Calculate(int numberOfDigits) {
    var a = new ArcTanWithBigRational();
    var b = new ArcTanWithBigRational();
    Task<BigRational> task1 = Task<BigRational>.Factory.StartNew(
                            () => a.Calculate(BigRational.Divide(1, 5),1000,numberOfDigits));
    Task<BigRational> task2 = Task<BigRational>.Factory.StartNew(
                            () => b.Calculate(BigRational.Divide(1, 239), 1000, numberOfDigits));

    var pi = 16 * task1.Result - 4 * task2.Result;

    return BigRationalPiFormatter.Format(pi, numberOfDigits);
}

The results this time:

Precision = 1000 digits
Number of iterations = 923
Elapsed Milliseconds = 1099

A little faster, but nothing to get excited about.

For completeness, here is my routine to format the BigRational Pi into a string:

public class BigRationalPiFormatter {
    public static string Format(BigRational pi, int numberOfDigits)
    {
        BigInteger numeratorShiftedToEnoughDigits =
                       (pi.Numerator * BigInteger.Pow(new BigInteger(10), numberOfDigits));
        var bigInteger = numeratorShiftedToEnoughDigits / pi.Denominator;
        string piToBeFormatted = bigInteger.ToString();
        var builder = new StringBuilder();
        builder.Append(piToBeFormatted[0]);
        builder.Append(".");
        builder.Append(piToBeFormatted.Substring(1, numberOfDigits - 1));
        return builder.ToString();
    }
}

Posted in .NET, Algorithms | Tagged: , , , | 2 Comments »