Just Behave! Part 2 of 2

In the previous post, we built the steps necessary to convert our coded HelloWorld test into a NBehave test.

In this post, we will build the NBehave test runner and use the steps we built in the previous post to run our HelloWorld test. To accomplish this we need 2 things.

  • Extensions class that contains methods for kicking off and validating results of the tests.
  • Feature files.

Extensions Class

Create a new class in the HelloWorld project named Extensions.cs.

The first method we will add is the ExecuteTest method.

public static FeatureResults ExecuteTest(this string path)
{
    return NBehaveConfiguration
        .New
        .DontIsolateInAppDomain()
        .SetEventListener(new OutputEventListener(new ConsoleWriter()))
        .SetAssemblies(new[] { typeof(HelloWorld.Google).Assembly.Location })
        .SetScenarioFiles(new[] { path })
        .Build()
        .Run();
}

This code sets up and kicks off a NBehave test and returns the results.

Next we need a method to validate the results.

public static void AssertTestResults(this FeatureResults results)
{
    if (results.NumberOfScenariosFound == 0)
        Assert.Inconslusive("No scenarios have been run");
    else
        Assert.AreEqual(results.NumberOfScenariosFound, results.NumberOfPassingScenarios);
}

This code returns an inconclusive result if no scenarios have been run. If scenarios have been run, we compare the number of scenarios ran to the number of scenarios that passed to determine if our tests passed or failed.

Next we need to build our .feature files. Feature files are the files that contain the NBehave tests. They are just regular old text files with a .feature extension.

Using Windows explorer, create a file named Google.feature in the same folder as the HelloWorld project. Then in the VS solution explorer right click on the HelloWorld project and select Add -> Existing Item… and add the new file to your project.

Add the following text to Google.feature:

Feature: Google
Validate Google functionality
	Scenario: Search for "Hello World!"
		Given a Firefox browser
		When I visit http://www.google.com/
		And I search for "Hello World!"
		Then the help button exists

This text defines a feature, “Google”, whose purpose is to “Validate Google functionality”. The scenario were testing is “Search for ‘Hello World!'” and the rest of the file contains references to the steps we built in part 1 of this tutorial.

The last thing to do is to change the SearchForHelloWorld method in the Google class from a coded test to an NBehave test runner. Replace the SearchForHelloWorld method with this method.

[TestMethod]
public void SearchForHelloWorld()
{
    string test = Environment.CurrentDirectory + @"\Google.feature";
    test.ExecuteTest().AssertTestResults();
}

When you kick off the SearchForHelloWorld test, its now driven by the feature file and executed with the NBehave steps!