Book Image

ServiceStack 4 Cookbook

Book Image

ServiceStack 4 Cookbook

Overview of this book

Table of Contents (18 chapters)
ServiceStack 4 Cookbook
Credits
About the Authors
About the Reviewers
www.PacktPub.com
Preface
Index

Integrating NUnit


The next step is to integrate a testing framework. We'll make use of the NUnit library in the examples in this book, though ServiceStack does work with almost any testing framework. First, add a new project to our solution. Call it <SolutionName>.Tests, substituting in the name of the package that you will test. Choose Class Library as the type. In Package Manager Console, choose <SolutionName>.Tests from the Default Project dropdown, and then type Install-Package nunit. You'll need to add a reference to ServiceStack from the test project as well—you can do that by typing Install-Package servicestack in Package Manager Console, as you did previously.

Now that you have a test project, you can start adding test classes. Generally, the idea is to create a test class for each grouping of tests—often, this means one test class per object under test. Create a new class inside your test project, then place the annotation [TestFixture] above the class declaration. Make sure you add the using declaration for NUnit.Framework, then add the annotation. If you were creating a test fixture to test GreetingService for instance, your code until now should look like this:

[TestFixture]
public class GreetingServiceTest
{
  
}

Then, you can add a method ShouldHaveWorkingTests, for instance, which proves your test environment is working. We'll decorate the method with the [Test] annotation like this:

[TestFixture]
public class GreetingServiceTest
{
  [Test]
  public void ShouldHaveWorkingTests()
  {
    Assert.AreEqual(false, true, "Can make assertions");
  }
}

Note

Note on NUnit and Visual Studio Express:

Visual Studio Express can easily help you to write NUnit tests, but the popular NUnit Test Adapter extension to run NUnit tests doesn't work with the Express version at the time of writing. To work around this, download either nunit-gui.exe or nunit-console.exe. Once you compile your tests, you can find the test assembly with NUnit and run your tests that way. If you're using a non-Express version of Visual Studio, the extension is highly recommended.

When using AppSelfHostBase, you will need to run the NUnit GUI as administrator for the tests to have sufficient privileges to host an HTTP application on the local machine.

If you're using the NUnit GUI, the test assembly might look like this:

This test should fail of course, proving that your test environment works. You can correct that by simply changing false to true.

[TestFixture]
public class GreetingServiceTest
{
  [Test]
  public void ShouldHaveWorkingTests()
  {
    Assert.AreEqual(true, true, "Can make assertions");
  }
}