Writing your first tests

Writing tests for your code isn’t difficult. It’s simply a matter of fixtures, tests and asserts.

With that knowledge in your head, let’s write a few tests for an application to help you win at the classic fizzbuzz game. The rules are easy.

To keep things simple, we’ll just write the first few tests for a simple static method called ToFizzBuzz() that takes an integer as an argument and returns the correct fizzbuzz string.

Setting Up The Solution

There are two options when it comes to organising your test code in your solution

First you’ll need to create two projects, one for the production code containing ToFizzBuzz() and one for the test code.

  1. Open up Visual Studio and create a new c# class library solution. We've called it FizzBuzz and renamed class1.cs to fizzbuzz.cs .
  2. Once it has been created, add another c# class library project to the solution called FizzbuzzTests and renamed class1.cs to fizzbuzztests.cs.
  3. Add a reference to MbUnit.Framework.dll to the FizzBuzzTests project. You'll find it in the .NET tab.
    Adding MbUnit as a reference in VS
  4. You'll also need to add a reference to the FizzBuzz project to FizzBuzzTests.
  5. Solution explorer should now look something like this
    Your solution setup ready for writing tests

That's you all set up. Now all you need to do are write tests and some code.

Writing the Tests

With the project setup, writing the tests is straightforward.

And so on. The point here is not how to write the best implementation of ToFizzBuzz() - there are several equally good ones - but that writing tests is not any different from writing another piece of code. The key is that your tests must be correct before your code can be. If we added [Row(15)] to this latest test, it would expect ToFizzBuzz() to return "fizz" rather than "fizzbuzz" as it should.

What MbUnit provides you with are methods such as the row test to let you perform these tests with the minimum of coding required. To that extent, the MbUnit.Framework library offers a great number of asserts for checking values, arrays, collections, data, files and more for you to use and a number of different test types in addition to the vanilla [Test] and strawberry flavoured [RowTest] you've seen here. It also lets you specify a test’s author or category for review later on. Perhaps you'll want to stop a few tests running for a while or flag issues with a test during a run? You can do that too with ignore flags and warnings.

Everything mentioned here and a lot more is covered in our API reference in detail. If you're not sure what to start, perhaps you should check out this rough guide.

More Step by Step guides

Check out our articles page for more step by step guides to writing code using tests.