Exercise: Unit testing, getting started (again)

I assume you have done a little unit testing of C# classes, some time ago ...

This exercise is supposed to refresh you knowledge on unit testing and add to this knowledge.

Getting started

Make the class to be tested

Before starting this part of the exercise: Please write down the starting time.

  1. Make a new project in Visual Studio, make it either Console Application or Library (we are not going to make any GUI in this project). Call the project School.
  2. Make a simple class Student with a few properties like name and age.
  3. Add a constructor with 2 parameters (name, age) to the Student class.
  4. Add a ToString() method to the Student class.

What is the time now? How much time did you spend on this exercise?

Make the test class

Before starting this part of the exercise: Please write down the starting time.

  1. In Visual Studio add a Unit test project. Call the project SchoolTest.
  2. Rename the test class in the newly created project, StudentTest
  3. Test your properties using Assert.AreEqual(expected, actual). You may also use other methods from the Assert class.
  4. Run the test.
  5. Add another test method to test the constructor.

What is the time now? How much time did you spend on this exercise?

Adding an equals() method

Before starting this part of the exercise: Please write down the starting time.

Add two equals() methods to the Student class. Make sure the Student class implements the interface IEquatable<T>. An example.

A two test methods to StudentTest to test the two equals() methods

What is the time now? How much time did you spend on this exercise?

Test coverage

Visual Studio has a feature to check which lines has be executed by you test.

Read the article Using Code Coverage to Determine How Much Code is being Tested and try it on your project.

Keep on adding new test cases to you test until you have a perfect cover i.e. all lines of you class has been executed by the test.

Having a perfect cover is nice, but it does not guarantee that you program is correct!

Parameter checking

Before starting this part of the exercise: Please write down the starting time.

The Student class should have a few class invariants

These invariants must be inforced in the properties (set) and the constructor in the Student class:

What is the time now? How much time did you spend on this exercise?

Testing the excetions thrown

Before starting this part of the exercise: Please write down the starting time.

Now you must add to the tests, to check that exceptions are thrown as expected.

Use the idiom

try { 
  obj.SomeExceptionThrowingMethod(); 
  Assert.Fail(); 
} 
catch (SomeException ex) { 
  Assert.AreEquals("some message", ex.Message); 
}

You should also try to the [ExpectedException(typeof(ArgumentException))] annotation

What is the time now? How much time did you spend on this exercise?