ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel
  • »
  • Technology»
  • Computers & Software»
  • Computer Science & Programming

Unit Testing width Visual Studio

Updated on June 23, 2016

Unit testing allows you to measure and test the classes you’ve created in Visual Studio without the need to run your full application. Here you will learn the basics of implementing unit tests in your applications.While this page is aimed at the newbie to unit testing, it assumes you have fundamental knowledge of the C# language and the Visual Studio IDE.

Introduction

While there are many third-party unit testing packages out there, Visual Studio has upped their game in the last few years and their integrated unit testing module has become quite efficient. So, using a third-party package is more a matter of choice than necessity. Here we will use the Visual Studio unit testing module which has the benefit that it’s already installed and fully integrated with your Visual Studio IDE.

Unit Testing and Test Driven Development

Unit testing is simply the act of testing an existing class. In Test Driven Development (TDD), the unit test is created before the class. For example, in an enterprise setup, an analyst might create the unit test then pass it on to a developer as a guide for creating a class that satisfies the unit test.

However, in a smaller development team or project, the choice is really yours. Do you first want to create your classes and then test them or create the tests and build your classes to meet the requirements of the tests?

Setup the Test Application

First we need an application with some classes to test. For our purposes, a simple console application will do. We’ll create an app that deposits money into a virtual bank account.

1. Open Visual Studio
2. Go to FILE > New > Project
3. Under the Visual C# templates, select Console Application
4. Give it a meaningful name such as Bank and click Ok
5. After the solution is generated, right-click the Bank project under the Solution
6. Explorer and select Add > Class
7. Name the new class BankAccount.cs and click Ok

Your unit test needs to access the BankAccount class from outside the Bank project, so change the BankAccount class’ access modifier to public. Also add a Balance property, a constructor, and a Deposit method as shown in the code sample below.

namespace Bank
{
    public class BankAccount
    {
        public decimal Balance { get; set; }

        public BankAccount(decimal balance)
        {
            Balance = balance;
        }

        public void Deposit(decimal amount)
        {
            Balance += amount;
        }
    }
}

We’re not really going to run the application, but we are going to test the class. So, you must build the Bank project to make sure it compiles and that the assembly can be referenced.

Creating the Test Project

Your unit tests will be in a separate project/assembly in the solution. After all it’s very rare that you want to deploy your unit tests with your application project.

1. In the Solution Explorer, right-click on Solution ‘Bank’ (1 project) at the top
2. Select Add > New Project
3. From the Visual C# Test templates select Unit Test Project
4. Give it a meaning name like BankUnitTests and click OK

The new unit test project is added to your solution with a default UnitTest1.cs class. Right-click this class and rename it to BankAccountTest.cs. Click yes on the pop-up message to rename it everywhere in your project.

Your unit test project will also need a reference to your Bank project to access the BankAccount class for testing.

Under the BankUnitTests project, right-click References and select Add Reference. The Reference Manager window will pop up. Under Solution > Projects, tick the Bank project and click Ok.

If you followed along with the naming, your solution should now look like this:

Open the BankAccountTest.cs class and add a using Bank statement to your usings.

Adding Tests

For our BankAccount class, we want to assert that the deposit method actually increases the account’s balance and that it does so correctly.

When you open the BankAccountTest.cs class in the BankUnitTestsProject, notice that the class is adorned with [TestClass] and the test methods are adorned with [TestMethod]. Other than that, it’s pretty much a class like any other.

First, you should give the test methods meaningful names since the method name will be listed in the Test Explorer results. For our test, let’s rename the method to Deposit_Increases_Balance_Correctly. Don’t be afraid to give these methods long descriptive names. Remember you will be the one reading the test results. If for example the method’s name was TestMethod1 and it fails, the test result would read “TestMethod1 Failed”. This is arbitrary and meaningless. A message like “Deposit_Increases_Balance_Correctly Failed” holds a lot more meaning for the tester.

Inside our test method we’ll first run the BankAccount.Deposit() method as you would normally. We’ll keep track of the original balance, the deposit amount, and the expected new balance. After running the deposit method, we’ll assert that the new balance on the account matches the expected balance.

using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Bank;

namespace BankUnitTests
{
    [TestClass]
    public class BankAccountTest
    {
        [TestMethod]
        public void Deposit_Increases_Balance_Correctly()
        {
            decimal originalBalance = 100.25m;
            decimal depositAmount = 50.00m;
            decimal newBalance = originalBalance + depositAmount;

            var account = new BankAccount(originalBalance);

            account.Deposit(depositAmount);

            Assert.AreEqual(newBalance, account.Balance);
        }
    }
}

The Assert is what does the actually testing, and it has several methods. In this case we’re checking if the changed balance on the account matches the expected value, using the Assert.AreEqual() method. Now’s a good time to Rebuild you Solution.

Running the Tests

If your Test Explorer is not already open, from the IDE menu select TEST > Windows > Test Explorer. You should see your test method listed in the Test Explorer.

From here you can select an individual test or simply run them all. Let’s run them all by clicking Run All.

The green check next to our test indicates the test was successful. It also shows next to it how long it took to run the test.

Let’s look at a failure. We’ll change the Deposit() method in the BankAccount class in the Bank project. Let’s assume the developer made a typo and subtracts the deposit amount instead of adding it.

public void Deposit(decimal amount)
{
    Balance -= amount;
}

Build your application again and run the test from the Test Explorer. Now notice the failure. There’s obviously something wrong with the deposit method.

The compiler is even smarter than that. If you open the BankAccount.cs class in your Bank project, you’ll notice the compiler marked the possibly places that could’ve caused the test failure.

Let’s add another test method. You’ll have to add a test method for each specific action you are testing. But first, change the Deposit() method in the BankAccount.cs class in the Bank project as shown in the code sample.

public bool Deposit(decimal amount)
{
       if (amount <= 0.00m) return false;

       Balance += amount;

       return true;
}

Now, add another test method to the BankAccountTest.cs class in your unit test project.

[TestMethod]
public void Deposit_Fails_With_Amount_Less_or_Equal_to_Zero()
{
    var account = new BankAccount(100.25m);

    var depositResult = account.Deposit(0.00m);

    Assert.IsFalse(depositResult);
}

Remember to adorn the method with [TestMethod], or the Test Explorer won’t recognize it as a test. Rebuild your solution and see the new test method in the Test Explorer.

Final Word

Hopefully this short introduction to unit testing has shown you how simple, easy and rewarding unit testing can be. From here you should dig deeper into the various Assert methods. A good starting place would be MSDN (Microsoft Developers Network).

About the Author

James Lombard has more than 20 years experience as a developer in the IT industry. He holds a degree in Information Technology and is a Microsoft Certified Specialist.

Comments

    0 of 8192 characters used
    Post Comment

    No comments yet.

    Click to Rate This Article