Unit Tests When and How

Unit Tests are a way to ensure the logic of your classes are producing the expected results. Those tests can be run from Visual Studio without having to load up the entire application manually then navigating to a specific section and trying to reproduce various scenarios.

There are some widely used naming conventions, for the assembly name it is often used as:

    [AssemblyName].Tests

The test files are often named as:

    [ClassName]Tests

And finally the methods are named as:

    UnitOfWork_StateUnderTest_ExpectedBehavior

So if I have, for example:

  1. CodingWise.Core    
  2. |- Roman.cs    
  3.    |- ConvertFrom  // method    
  4.    |- ConvertTo    // method  
I will have a test assembly with the following files:
  1. CodingWise.Core.Tests    
  2. |- RomanTests.cs    
  3.    |- ConvertFrom_Decimal1_ReturnsI  // method    
  4.    |- ConvertFrom_Decimal9_ReturnsIX // method    
  5.    |- ConvertTo_RomanIV_Returns4     // method    
  6.    ...    
Unit tests classes and methods must be decorated with attributes. For classes you need to specify that it is a test class with the following attribute:
  1. TestClass   
On methods you need to use the following attribute:
  1. TestMethod   

  1. [TestClass]    
  2. public class RomanConverterTests    
  3. {    
  4.     [TestMethod]    
  5.     public void ConvertFrom_Decimal1_ReturnsI()    
  6.     {    
  7.         Assert.AreEqual("I", Roman.ConvertFrom(1));    
  8.     }    
  9. }   
Assert provides several methods to compare actual results to expected results and if it fails it will throw a notification on the Test Explorer window. Asserts shouldn't be overused on a single method. It is ok to use more than one Assert but you need to be careful not to test multiple things in the same method.

There are the following four other attributes for methods that are not required but they can be quite useful:

ClassInitialize runs once before all tests.
  1. ClassInitialize   Runs once before all tests.    
  2. ClassCleanUp      Runs once after all tests.    
  3. TestInitialize    Runs before you run each test.    
  4. TestCleanUp       Runs after you run each test.   
It is most useful when you want to do a database test. You can create a transaction and then rollback. This way you test the logic and don't pollute/corrupt the database.
  1. [TestClass]    
  2. public class UserServiceTests    
  3. {    
  4.     private ApplicationContext db;    
  5.      
  6.     [TestInitialize]    
  7.     public void TestInitialize()    
  8.     {    
  9.         db = new ApplicationContext();    
  10.         db.Database.BeginTransaction();    
  11.     }    
  12.      
  13.     [TestCleanup]    
  14.     public void TestCleanUp()    
  15.     {    
  16.         db.Database.CurrentTransaction.Rollback();    
  17.         db.Dispose();    
  18.     }    
  19.      
  20.     [TestMethod]    
  21.     public void Save_AllFields_Completes()    
  22.     {    
  23.         var userService = new UserService { Context = db };    
  24.         var user = new User();    
  25.      
  26.         user.Username = "brunolm";    
  27.         user.Name = "BrunoLM";    
  28.         user.Email = "[email protected]";    
  29.      
  30.         userService.Save(user);    
  31.     }    
  32. }   
There are also “mocks”. The purpose of mocks is to provide external information to your test so you can complete a unit of work. In the following example I'm mocking an:
  1. IItem   
because it doesn't really matter to the unit of work being tested. The service wasn't mocked because that is under test and what I'm checking here is if the service has the correct logic that is only allowing buyable items to be added to the cart.

The following example uses Moq.
  1. public class CartService    
  2. {    
  3.     public ApplicationContext Context { getset; }    
  4.      
  5.     public IList<IItem> Items { getset; }    
  6.      
  7.     public CartService()    
  8.     {    
  9.         Items = new List<IItem>();    
  10.     }    
  11.      
  12.     public void Add(IItem item)    
  13.     {    
  14.         if (!item.Buyable)    
  15.             throw new ArgumentException("This item can't be bought.""item");    
  16.      
  17.         Items.Add(item);    
  18.     }    
  19. }    
  20.      
  21. public interface IItem    
  22. {    
  23.     bool Buyable { getset; }    
  24. }    
  25.      
  26. [TestClass]    
  27. public class CartServiceTests    
  28. {    
  29.     [TestMethod]    
  30.     [ExpectedException(typeof(ArgumentException))]    
  31.     public void Add_NonBuyable_Throws()    
  32.     {    
  33.         var cartService = new CartService();    
  34.      
  35.         var mock = new Mock<IItem>();    
  36.         mock.SetupProperty<bool>(item => item.Buyable, false);    
  37.      
  38.         cartService.Add(mock.Object);    
  39.     }    
  40.      
  41.     [TestMethod]    
  42.     public void Add_Buyable_Includes()    
  43.     {    
  44.         var cartService = new CartService();    
  45.      
  46.         var mock = new Mock<IItem>();    
  47.         mock.SetupProperty<bool>(item => item.Buyable, true);    
  48.      
  49.         cartService.Add(mock.Object);    
  50.      
  51.         Assert.AreEqual(1, cartService.Items.Count);    
  52.     }    
  53. }    
Mocks are sometimes overused, be careful not to fall on “Unit Test Only Tests the Mock” situation. Mocks exist to eliminate external dependencies and allow your code to focus on a single unit of work.

On MVC you will find examples of mocks for controller contexts, HTTP contexts and so on.

So always remember to choose good names, limit the scope of your test and use mocks with responsibility.


Similar Articles