Unit Tests



If you are anything like me, you are not a fan of writing unit tests, but appreciate the gift they give when written properly. See the girl in the picture? She is most definitely writing unit tests .... half grin with a little 'go away' on her face.


During an interview, I was asked if I knew what 'Triple A' was. Of course I answered 'sure, you call them when you need a tow or a jump start!' .... this was obviously the wrong answer, but I did get a good laugh from my interviewer



Triple A refers to the unit testing structure 'Arrange, Act, Assert'. I know this now :)


One thing I have found over the years is that when you decide the scaffolding for your unit test suite, it is best to decide on using 1 framework or things can get messy. When you use Microsoft Fakes and NUnit (or XUnit or any other framework), you can have some unintended consequences and complications of successfully testing your code. You may end up having to basically hard code your test objects instead of constructing them as intended.


If you are unfamiliar with unit tests, a great place to start is Pluralsight. I highly recommend the testing path here if you have a subscription. If you are looking for the free tutorial, NUnit has some pretty good documentation on how to learn the basics.


An example taken from the NUnit documentation is below.



namespace Bank
{
  public class Account
  {
    private decimal balance;
	
    public void Deposit(decimal amount)
    {
      balance += amount;
    }

    public void Withdraw(decimal amount)
    {
      balance -= amount;
    }

    public void TransferFunds(Account destination, decimal amount)
    {
    }

    public decimal Balance
    {
      get { return balance; }
    }
  }
}

Now after we've written the base code, we want to test if the TransferFunds() method. The basic structure includes the TextFixture decorator on the class, and Test decorator on each test.


If you wish to not run a test, you can comment out the Test decorator on the test and it will be skipped.


namespace Bank
{
  using NUnit.Framework;

  [TestFixture]
  public class AccountTest
  {
    [Test]
    public void TransferFunds()
    {
      Account source = new Account();
      source.Deposit(200m);
      
      Account destination = new Account();
      destination.Deposit(150m);

      source.TransferFunds(destination, 100m);
	  
      Assert.AreEqual(250m, destination.Balance);
      Assert.AreEqual(100m, source.Balance);
    }
  }
}

This should get you a decent start on where to find more information on unit tests and how to write them accurately. Make sure you are keeping in mind WHAT you are testing, sometimes we can get stuck in the weeds and end up testing almost nothing. Test your return statements and any error paths. That's a great place to start!

Tags: