ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel

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.

    working

    This website uses cookies

    As a user in the EEA, your approval is needed on a few things. To provide a better website experience, hubpages.com uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

    For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at: https://hubpages.com/privacy-policy#gdpr

    Show Details
    Necessary
    HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
    LoginThis is necessary to sign in to the HubPages Service.
    Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
    AkismetThis is used to detect comment spam. (Privacy Policy)
    HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
    HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
    Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
    CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
    Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the googleapis.com or gstatic.com domains, for performance and efficiency reasons. (Privacy Policy)
    Features
    Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
    Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
    Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
    Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
    Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
    VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
    PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
    Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
    MavenThis supports the Maven widget and search functionality. (Privacy Policy)
    Marketing
    Google AdSenseThis is an ad network. (Privacy Policy)
    Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
    Index ExchangeThis is an ad network. (Privacy Policy)
    SovrnThis is an ad network. (Privacy Policy)
    Facebook AdsThis is an ad network. (Privacy Policy)
    Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
    AppNexusThis is an ad network. (Privacy Policy)
    OpenxThis is an ad network. (Privacy Policy)
    Rubicon ProjectThis is an ad network. (Privacy Policy)
    TripleLiftThis is an ad network. (Privacy Policy)
    Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
    Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
    Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
    Statistics
    Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
    ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
    Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)