OK so I have the following classes in C#:
class Program
{
static void Main(string[] args)
{
MyClass myClass = new MyClass("Hello World");
myClass.WriteToConsole();
}
}
class MyClass
{
private string MyProperty { get; set; }
public MyClass(string textToEncapsulate)
{
MyProperty = textToEncapsulate;
}
public void WriteToConsole()
{
Console.WriteLine(MyProperty);
}
}
Three questions:
- What is unit testing?
- Would unit testing be beneficial in the above example?
- How would I go about ‘Unit Testing’ the above example?
Thanks
1. What is unit testing?
Manual testing is time consuming. It can be hard to run the exact same set of tests each time by hand to make sure that all parts of your code are functioning as expected. When testing a complete product by hand, it’s also really hard to test all code paths.
How would you test the reaction of your code when a database is unavailable? Or when some erroneous data is stored? That would take quite some time to get right.
Unit Testing means that we start testing the smallest possible parts of our code. And to make sure we can do this easily we automate the process. This means that we write test code that tests our production code.
For example:
This tests assures that your Sum function on your Calculator class is working correctly.
Now, let’s say that you want to optimize the inner workings of your Calculator class. You start changing and optimizing code. After each change you run your unit test and when they all succeed you know you haven’t broken any code.
Let’s say that in production a user submits a bug report for your Calculator. Your first step will be to write a unit test that shows this bug. After the new test is failing (because the bug is still there!) you fix the bug, the unit tests succeeds and you can be certain that this bug will never come back.
This safety harness is one of the biggest benefits of unit tests.
2 Would unit testing be beneficial in the above example? 3 How would I go about ‘Unit Testing’ the above example?
Unit Testing is a good practice. It helps you prove that your code is working. In your example however, it would be hard to test the code.
An output to the console is not something that can be easily tested. If however, you would abstract the idea of Console.WriteLine then your code becomes better testable.
Writing Unit Tests is actually quite simple. The problem is writing code that can actually be tested.
A better testable version of your code would be:
You have replaced your direct dependency on the Console with an interface. When unit testing this code, you could supply a fake for your IOutputService and check the outcome.
A really good book is xUnit Test Patterns. It shows the common pitfalls in writing unit test and patterns to avoid/fix them.
I also wrote a blog myself about testable code a couple of months ago. It’s somewhat more advanced but maybe you can get something out of it. If you have any questions, feel free to ask.