Share via


C#: Getting Started with Test Driven Development

Introduction

Test Driven Development (TDD) is a highly recommended approach to software development. In TDD, we first write unit tests, generate skeleton code so that the solution builds. Obviously, all tests will fail initially since we have no functional code in place as yet!

Taking Flight

We now need to write the functional code so that all tests pass. This does sound simple but possibly we will have to refactor our code iteratively, and in most situations, we will also need to mock certain services so that our tests execute without actually say touch the databases, etc.

Let's see a sample console app to understand the steps involved:

  1. Create a console app:

  2. Add Unit Test project:

    You will see the Test Project in the Solution Explorer:

    Note: don't forget to add a reference to the C# project in your Test project!

  3. Add the Test method & write code to essentially fail the target method. Ideally, it should cover all possible flows/scenarios (we can see the test passing below because I already had the functional code in place but you will get this test as failed initially):

  4. Add functional code:

  5. Run the tests!

See also

Different methods to display unit test 

External resources 

Unit test your code 
Get started with Live Unit Testing in Visual Studio 

Code Sample

You can get sample code for this article from http://code.msdn.microsoft.com/Getting-Started-with-Test-18a7624b