Hullo folks! :)
In yesterday's article, "C#: Unit Testing with SharpDevelop and NUnit", we learned about unit tests: what they are, why we use them, and how we write and execute them. The article ended with a number of insights about them. One of these insights was that it is not easy to write unit tests for code that relies on databases, the network, or other external resources.
In today's article, we're going to address this problem by learning about mocking and dependency injection. These might sound like big buzz-words, but you'll see in this article that they're really nothing special. To see this in action, we'll write a small program that loads a file from the hard disk and sorts it alphabetically, line by line.
This article is a bit on the advanced side, so ideally you should know your OOP and also be familiar with basic unit testing (e.g. from yesterday's article) before reading it.
Start off by creating a new Console Application in SharpDevelop. When this is done, add a new class (right click on project in Projects window, Add -> New Item...) and name it Sorter. At the top, add the following to allow us to read files and use lists:
using System.Collections.Generic;
using System.IO;
Next, add a member variable in which we can store the lines in the file:
private String[] lines;
Add a constructor in Sorter that takes the name of the file to sort, and loads it into the variable we just declared:
public Sorter(String filename)
{
this.lines = File.ReadAllLines(filename);
}
Now, add a method that actually does the sorting:
public String[] GetSortedLines()
{
List<String> sortedLines = new List<String>(lines);
sortedLines.Sort();
return sortedLines.ToArray();
}
This way of sorting is not the only one and not necessarily the best, but I chose it because it's simple and doesn't change the lines variable, just in case you want to keep it in its original unsorted format for whatever reason.
Let's try and write a test for this code. Add a new class called SorterTest (as I've already mentioned in yesterday's article, people usually put tests into their own project, but I'm trying to teach one concept at a time here). After adding a reference to nunit.framework.dll (check yesterday's article in case you're lost), set up the SorterTest.cs file as follows:
[Test]
public void GetSortedLinesTest()
{
Sorter sorter = new Sorter("test.txt");
String[] s = sorter.GetSortedLines();
Assert.AreEqual("Gates, Bill", s[0]);
Assert.AreEqual("Norris, Chuck", s[1]);
Assert.AreEqual("Torvalds, Linus", s[2]);
Assert.AreEqual("Zuckerberg, Mark", s[3]);
}
Create a file in your bin\Debug folder called test.txt and put the following in it:
Zuckerberg, Mark
Norris, Chuck
Gates, Bill
Torvalds, Linus
Open the Unit Tests window in SharpDevelop (View -> Tools -> Unit Tests) and run it. You can see that the test passes.
Great.
Actually, this is the wrong way of writing unit tests for this kind of thing. We have a dependency on the filesystem. What would happen if that file suddenly disappears? As a matter of fact, we are supposed to be testing the sorting logic, not whether the file is available or not.
In order to do this properly, we're going to have to refactor our code. We need to take our file loading code out of there. Create a new class called FileLoader and add the following at the top:
using System.IO;
...and then set up FileLoader as follows:
public class FileLoader
{
private String[] lines;
public String[] Lines
{
get
{
return this.lines;
}
}
public FileLoader(String filename)
{
this.lines = File.ReadAllLines(filename);
}
}
In Sorter, remove the constructor as well as the using System.IO; and the lines variable. Instead, we'll pass our FileLoader as a parameter:
public String[] GetSortedLines(FileLoader loader)
{
List<String> sortedLines = new List<String>(loader.Lines);
sortedLines.Sort();
return sortedLines.ToArray();
}
This is called dependency injection: instead of creating the dependency (in our case a file) from within the Sorter class, we pass it as a parameter. This allows us to substitute the dependency for a fake (known as a mock). To do this, we'll need to take advantage of polymorphism (see "C# OOP: Abstract classes, fruit, and polymorphism". Create an interface (when adding a new item, instead of Class, specify Interface) and name it IFileLoader:
An interface is a form of abstract class - it cannot be instantiated, and it declares methods and/or properties that don't have any implementation because they should be implemented by the classes that inherit from (or implement) that interface. In an interface, however, no methods/properties have an implementation. It is used as a contract, saying that any class implementing the interface must implement its methods/properties. In our case, IFileLoader will be this:
public interface IFileLoader
{
String[] Lines
{
get;
}
}
We then specify that FileLoader implements IFileLoader; this is the same as saying that FileLoader inherits from IFileLoader:
public class FileLoader : IFileLoader
FileLoader already has the necessary Lines property, so we're fine. Next, we replace the FileLoader parameter in Sorter.GetSortedLines() with an instance of the interface:
public String[] GetSortedLines(IFileLoader loader)
This allows us to pass, as a parameter, any class that implements IFileLoader. So we can create a class, MockFileLoader, that provides a hardcoded list of names:
public class MockFileLoader : IFileLoader
{
private String[] lines = { "Zuckerberg, Mark", "Norris, Chuck", "Gates, Bill", "Torvalds, Linus" };
public String[] Lines
{
get
{
return this.lines;
}
}
}
We can now rewrite our unit test like this:
[Test]
public void GetSortedLinesTest()
{
IFileLoader loader = new MockFileLoader();
Sorter sorter = new Sorter();
String[] s = sorter.GetSortedLines(loader);
Assert.AreEqual("Gates, Bill", s[0]);
Assert.AreEqual("Norris, Chuck", s[1]);
Assert.AreEqual("Torvalds, Linus", s[2]);
Assert.AreEqual("Zuckerberg, Mark", s[3]);
}
If you run the unit test, you'll find that it works just like before, just that this time our unit test isn't dependent on any file and can run just file without one:
In this article, we have seen how to create mock classes that emulate the functionality of our normal classes, but can replace them in unit tests when dependencies exist. To facilitate this, both the mock class and the normal class implement a common interface, and an instance of this interface is passed as a parameter to the method being tested. This is called dependency injection and allows us to control what is being passed to the method.
It is not always easy to write mocks. First, as this article has shown, code may need to be refactored in order to isolate dependencies and support dependency injection. Secondly, mocking complex classes (e.g. an IMAP server) can take a great deal of effort and might not necessarily be worth it. Use your own judgement to decide whether you need unit tests in such situations.
Thanks for reading, and be sure to visit here often to read more articles that might be useful.
Showing posts with label mocking. Show all posts
Showing posts with label mocking. Show all posts
Sunday, September 22, 2013
C#: Mocking and Dependency Injection for Unit Testing a File Sorting Program
Labels:
advanced,
bill gates,
chuck norris,
dependency injection,
files,
inheritance,
interfaces,
io,
linus torvalds,
lists,
mark zuckerberg,
mocking,
nunit,
oop,
polymorphism,
properties,
sharpdevelop,
sorting,
unit testing
Saturday, September 21, 2013
C#: Unit Testing with SharpDevelop and NUnit
Hey there! :)
In today's article I'm going to introduce unit testing, and show how basic unit tests can be written and run from within SharpDevelop. This is just one way of doing unit testing; Visual Studio's integrated unit testing suite is a pretty good alternative, or else you could use NUnit separately from your IDE; but let's not go there at this stage.
As usual, let's avoid lengthy overviews and learn about unit testing by doing it. To start off, create a new SharpDevelop project. Then, right click on the project in Solution Explorer and select Add -> New Item...; from there, add a new class called EmailAddress:
Set up the class such that it can be used to store an email address provided in its constructor:
public class EmailAddress
{
private String emailAddress;
public EmailAddress(String emailAddress)
{
this.emailAddress = emailAddress;
}
}
In the EmailAddress class, add a simple method to check whether the email address it contains is a valid one:
public bool IsValid()
{
if (this.emailAddress.Contains("@"))
return true;
else
return false;
}
Let's add also add some code in Main() that will allow us to test this manually:
public static void Main(string[] args)
{
Console.WriteLine("Enter your email address: ");
String emailStr = Console.ReadLine();
EmailAddress emailAddress = new EmailAddress(emailStr);
if (emailAddress.IsValid())
Console.WriteLine("Congratulations, your email is valid!");
else
Console.WriteLine("Oops, that's not a valid email address!");
Console.ReadKey(true);
}
Now, we could run the program several times, each time giving it a different email address to test it, but this would be tedious. Instead, we can write unit tests. These are normally kept in a separate project, but to keep things simple, we'll use the same project. Before we proceed, though, you'll need to download and install NUnit. When you're done, you should be able to find nunit.framework.dll in NUnit's bin\framework folder:
Back in SharpDevelop, from Solution Explorer, right click on the project and select Add Reference...:
In the window that appears, select the ".NET Assembly Browser" tab, hit the "Browse..." button, and locate the nunit.framework.dll file as above. This will allow you to use NUnit's functionality directly from within SharpDevelop.
Add a new class called EmailAddressTest and replace the default contents of the file with the following code:
using System;
using NUnit.Framework;
namespace CsSdUnitTesting
{
[TestFixture]
public class EmailAddressTest
{
[Test]
public void EmailAddressTest_Simple_Valid()
{
EmailAddress email = new EmailAddress("test@example.com");
bool isValid = email.IsValid();
Assert.IsTrue(isValid);
}
}
}
Note how, on the second line, we are using the NUnit.Framework namespace, which comes from the nunit.framework.dll to which we have just added a reference. This allows us to mark classes containing tests with the TestFixture attribute, and test methods with the Test attribute.
The method you see above is an example of a unit test: in it, we create an instance of our EmailAddress class, and test a particular method (in this case the IsValid() method). We hardcode an input, evaluate the method, and define an expected output using one of the many methods in the Assert class.
Let's actually run this unit test. Open the Unit Tests window by going to the View menu and then selecting Tools -> Unit Tests:
Once the Unit Tests window opens up on the right, you can just hit one of the Play buttons to run your tests:
Your unit tests should capture not only valid data, but also cases that are meant to fail. For example, this unit test catches invalid email addresses that are missing the '@' character:
[Test]
public void EmailAddressTest_NoAt_Invalid()
{
EmailAddress email = new EmailAddress("hello");
bool isValid = email.IsValid();
Assert.IsFalse(isValid);
}
When you run this test, you should get a green light just as before, showing that the test has passed.
Now, let's try a different test:
[Test]
public void EmailAddressTest_NoDomain_Invalid()
{
EmailAddress email = new EmailAddress("test@");
bool isValid = email.IsValid();
Assert.IsFalse(isValid);
}
This test is supposed to catch cases where there is no domain, and we expect it to be invalid. So we run the tests again:
Crap. Our test failed, so we need to go back and fix the code. When logic is complicated, you can set breakpoints in the tests and run the tests within the debugger, saving you from having to actually run the program itself (which may take time for more complex applications).
There are many ways to verify an email address, including using the MailAddress class or using a regular expression. In my case I wrote a simple regular expression which does not cover every case but is enough for what we need. I haven't covered regular expressions, but don't worry, just use this code for IsValid():
public bool IsValid()
{
if (Regex.IsMatch(emailAddress, @"\w+\@\w+(\.\w+)+"))
return true;
else
return false;
}
You will also need to put this at the top for it to work:
using System.Text.RegularExpressions;
If you run the tests now, they should all pass. If someone happens to change the regular expression in the future and breaks something, re-running the tests should allow you to detect the issue. Re-running a test to see whether something broke is called a regression test, and is a great way to detect problems early and fix them before they make it into a release.
In this article you have seen how unit tests are used, with the example of validating an email address. There is a lot more to say about unit tests, but this should suffice as an introduction. I will mention a few points however:
In today's article I'm going to introduce unit testing, and show how basic unit tests can be written and run from within SharpDevelop. This is just one way of doing unit testing; Visual Studio's integrated unit testing suite is a pretty good alternative, or else you could use NUnit separately from your IDE; but let's not go there at this stage.
As usual, let's avoid lengthy overviews and learn about unit testing by doing it. To start off, create a new SharpDevelop project. Then, right click on the project in Solution Explorer and select Add -> New Item...; from there, add a new class called EmailAddress:
Set up the class such that it can be used to store an email address provided in its constructor:
public class EmailAddress
{
private String emailAddress;
public EmailAddress(String emailAddress)
{
this.emailAddress = emailAddress;
}
}
In the EmailAddress class, add a simple method to check whether the email address it contains is a valid one:
public bool IsValid()
{
if (this.emailAddress.Contains("@"))
return true;
else
return false;
}
Let's add also add some code in Main() that will allow us to test this manually:
public static void Main(string[] args)
{
Console.WriteLine("Enter your email address: ");
String emailStr = Console.ReadLine();
EmailAddress emailAddress = new EmailAddress(emailStr);
if (emailAddress.IsValid())
Console.WriteLine("Congratulations, your email is valid!");
else
Console.WriteLine("Oops, that's not a valid email address!");
Console.ReadKey(true);
}
Now, we could run the program several times, each time giving it a different email address to test it, but this would be tedious. Instead, we can write unit tests. These are normally kept in a separate project, but to keep things simple, we'll use the same project. Before we proceed, though, you'll need to download and install NUnit. When you're done, you should be able to find nunit.framework.dll in NUnit's bin\framework folder:
Back in SharpDevelop, from Solution Explorer, right click on the project and select Add Reference...:
In the window that appears, select the ".NET Assembly Browser" tab, hit the "Browse..." button, and locate the nunit.framework.dll file as above. This will allow you to use NUnit's functionality directly from within SharpDevelop.
Add a new class called EmailAddressTest and replace the default contents of the file with the following code:
using System;
using NUnit.Framework;
namespace CsSdUnitTesting
{
[TestFixture]
public class EmailAddressTest
{
[Test]
public void EmailAddressTest_Simple_Valid()
{
EmailAddress email = new EmailAddress("test@example.com");
bool isValid = email.IsValid();
Assert.IsTrue(isValid);
}
}
}
Note how, on the second line, we are using the NUnit.Framework namespace, which comes from the nunit.framework.dll to which we have just added a reference. This allows us to mark classes containing tests with the TestFixture attribute, and test methods with the Test attribute.
The method you see above is an example of a unit test: in it, we create an instance of our EmailAddress class, and test a particular method (in this case the IsValid() method). We hardcode an input, evaluate the method, and define an expected output using one of the many methods in the Assert class.
Let's actually run this unit test. Open the Unit Tests window by going to the View menu and then selecting Tools -> Unit Tests:
Once the Unit Tests window opens up on the right, you can just hit one of the Play buttons to run your tests:
Your unit tests should capture not only valid data, but also cases that are meant to fail. For example, this unit test catches invalid email addresses that are missing the '@' character:
[Test]
public void EmailAddressTest_NoAt_Invalid()
{
EmailAddress email = new EmailAddress("hello");
bool isValid = email.IsValid();
Assert.IsFalse(isValid);
}
When you run this test, you should get a green light just as before, showing that the test has passed.
Now, let's try a different test:
[Test]
public void EmailAddressTest_NoDomain_Invalid()
{
EmailAddress email = new EmailAddress("test@");
bool isValid = email.IsValid();
Assert.IsFalse(isValid);
}
This test is supposed to catch cases where there is no domain, and we expect it to be invalid. So we run the tests again:
Crap. Our test failed, so we need to go back and fix the code. When logic is complicated, you can set breakpoints in the tests and run the tests within the debugger, saving you from having to actually run the program itself (which may take time for more complex applications).
There are many ways to verify an email address, including using the MailAddress class or using a regular expression. In my case I wrote a simple regular expression which does not cover every case but is enough for what we need. I haven't covered regular expressions, but don't worry, just use this code for IsValid():
public bool IsValid()
{
if (Regex.IsMatch(emailAddress, @"\w+\@\w+(\.\w+)+"))
return true;
else
return false;
}
You will also need to put this at the top for it to work:
using System.Text.RegularExpressions;
If you run the tests now, they should all pass. If someone happens to change the regular expression in the future and breaks something, re-running the tests should allow you to detect the issue. Re-running a test to see whether something broke is called a regression test, and is a great way to detect problems early and fix them before they make it into a release.
In this article you have seen how unit tests are used, with the example of validating an email address. There is a lot more to say about unit tests, but this should suffice as an introduction. I will mention a few points however:
- Unit tests allow you to test a single unit of functionality, often a method or property.
- As such, they work great with methods that have a clear input and output (such as a method which takes an email address in String format and returns a boolean indicating whether it is valid or not).
- Unit tests are not easy to write for methods which are not public, which are void, or which do not take parameters. In Visual Studio there is a way to get around this, but in NUnit you have to refactor your code.
- Unit tests are really tricky to write for methods which rely on external resources such as files, databases, or remote network locations. To make them work in such scenarios, techniques such as dependency injection and mocking come into play.
- Unit tests won't make your code bug-free, especially if you don't write unit tests to handle the majority of possible inputs. They won't solve all your problems, so use them only when they are worth the effort.
- Some people like to write unit tests before the actual development code - this is called Test Driven Development (TDD).
That's all, folks! Stick around, as articles are posted here regularly. :)
Subscribe to:
Posts (Atom)







