Wednesday, 22 January 2014

Learn basic unit testing with VS2012 and Nunit

This post is a guide for basics of Unit testing. Through this article we’ll go step by step setting up the Environment and few basic test scenarios. To start with hands on you need following installed on you machine.

Download

image

If you already have Visual studio installed then you need to install the Nuget Extension Manager extension of Visual studio.

Now you’re ready to install the libraries which are available on Official Nuget server. For this exercise we’ll be using Nunit testing framework. The nuget manager will Install the Nunit Framework and Nunit test adapter from the Visual studio itself. So like the old days you don’t have to go to web and download the Nunit package and then adding to the visual studio. Nuget is the new RAD tool that won’t let you go off the Visual studio Interface.

So now we have the tools so let’s get started:

1. Launch the visual studio and create new Class Library project.

image

2. Now let’s write some logical methods for e.g. just simple numeric and string operations.

public class LogicalClass
{
    /// <summary>
    /// A sample divide operation
    /// </summary>
    /// <param name="a">Any positive integer</param>
    /// <param name="b">A non zero value</param>
    /// <returns>result of divide operation as decimal</returns>
    public decimal Divide(int a, int b)
    {
        if (b == 0)
        {
          throw new DivideByZeroException("Lets ensure.");   
        }
 
        return (a / b);
    }
 
    /// <summary>
    /// The concat two names.
    /// </summary>
    /// <param name="name1"> The name 1. </param>
    /// <param name="name2"> The name 2. </param>
    /// <returns> The <see cref="string"/>. </returns>
    public string ConcatTwoNames(string name1, string name2)
    {
        return string.Format("{0}.{1}", name1, name2);
    }
}

Now since this is a class library and to ensure that my logic is working fine without debugging, We’ll write some more code which will unit test the methods.


3. Let’s proceed with creating a new project as Class library called DemoLibrary.UnitTests


image


Now before we start writing the unit tests for the LogicalClass we would need the Testing framework. You can also use the same Microsoft.Tests but I’m quite fond of Nunit. But there’s no such difference which framework you would use, If you’re interesting in comparing these two frameworks capabilities then you can visit the comparison list here.


4. To install the Nunit framework right click on the Unit test project and select Manage Nuget package. This will open the window showing the online Packages available. Search for Nunit and you’ll see the result shown as in below image.


image


Install the Nunit and Nunit Test Adapter for VS2012 & 2013. Why do we need test adapter? To find and run the Unit tests the Nunit test adapter will do the work for you. You can also install the extension of Nunit Test Adapter. Go to Extension Manager –> Search “Nunit Test Adapter” and Install.  Though Visual studio can also find tests and you can run them by going to menu Test –> Windows –> Test Explorer.


image


Now setup is finished so start writing the Unit tests. Let’s add a class named LogicalClassTests this is a naming convention you must follow as this will make your tests easily identifiable just by name of the Test class.


Now the test class will have following things you need to learn to make a test perfect looking and runnable.


image


TestFixture Class Attribute – This attribute is to mark a class as test suite which will contain tests.


Test Method Attribute – This attribute is to mark a method as a Unit test. Only methods with this attribute would be runnable by test runner.


Setup – To initialize the object to be tested and initial values required for the test. In upcoming article we’ll learn how to Fake/Mock the dependencies like Database, FileSystem, Or any other external system while writing tests. This will be the part of setup.


Act – Act is actually when you call the method that you’re going to test. So you provide the test values to the method and receive an output which will be tested against the expected result.


Assert – Assert is the statement which will check the expected values by the result.


Similarly, you’ll write the tests for all the positive scenarios of a method. To download the demo exercise files you can download them from here.


Source Code: https://db.tt/NwTlSIvu

Monday, 6 January 2014

Unit testing async marked methods using mock library

Have you ever tried unit testing a method marked with async? There’s a known problem of unit testing the Async marked methods. When Nunit tried to run the test with mocked Async methods it goes in Infinite wait. There are many discussion on the internet for the same giving you the solutions and work around. This post will provide you with another solution.

Let’s start and setup a test project to reproduce the problem. So first we need library that contains the methods marked with Async keyword.

First we need the marker interface:

IHttpDownloader.cs

public interface IHttpDownloader
{
    Task<string> DownloadContentAsync(Uri httpUri);
}

Implementation:


HttpDownloader.cs



public class HttpDownloader : IHttpDownloader
{
    public async Task<string> DownloadContentAsync(Uri httpUri)
    {
        RawHttpDownloader downloader = new RawHttpDownloader();
 
       return await downloader.DownloadAsync(httpUri);
    }
}

Helper class:


RawHttpDownloader.cs



public class RawHttpDownloader
{
    public async Task<string> DownloadAsync(Uri httpUri)
    {
        return string.Format("Dummy downloaded string from {0}", httpUri.AbsolutePath);
    }
}


Now lets write a unit test to test this method for a positive scenario. Here I have used the Nunit to write the tests:



[TestFixture]
public class HttpDownloaderTest
{
    [Test]
    public void DownloadContentAsync_ValidHttpAddress_ReturnsData()
    {
        var repository = new MockRepository();
        var httpUri = new Uri("http://www.google.com/about");
 
        var downloaderStub = repository.Stub<IHttpDownloader>();
 
        // setup
        var task = new Task<String>(
            () => { return "test string"; });
 
        downloaderStub.Expect(s => s.DownloadContentAsync(httpUri)).Return(task);
 
        // act
        repository.ReplayAll();
 
        var restult = downloaderStub.DownloadContentAsync(httpUri);
 
       Assert.IsNotNull(restult.Result);
 
        repository.VerifyAll();
    }
}

If you try to run this test It will go in Infinite state:


image


Problem caused by the Nunit framework as it doesn’t support the methods marked with Async keyword for tests. So it kept on waiting for the asynchronous method and it actually never invokes the Task returned into start state.


Solution:


Since the Nunit doesn’t actually invokes the underlying task to start state so you what you just have to do is Start the task manually.


image


 


Download the complete sample from here.