dotnet thoughts 

a dotnet developer's technical blog

Getting Code coverage using Open Cover and NUnit

In the last post I blogged about how to get code coverage using MSTest and Part cover. In this post I am blogging about measuring code coverage with Open cover. Today I found another alternative to measure code coverage. Its called Open cover. You can download Open Cover from here. Compared to Part cover, Open cover doesn’t have a UI part. Also open cover gives better performance compared to Part cover. You can find Performance comparison here. You can find the OpenCover command line parameters in Github wiki.

In this example I am using a NUnit as the unit testing application. And the following command gets the code coverage in XML file.

"C:\Program Files (x86)\OpenCover\OpenCover.Console.exe"
-filter:"-[DataAccess.*]* +[DataAccess*]* -[DataAccess.Test]"
-target:"C:\Program Files (x86)\NUnit 2.5.10\bin\net-2.0\nunit-console-x86.exe"
-register:user -targetargs:"/nologo DataAccess.Test.dll"
-output:coverage.xml

The filter part is similar like, PartCover application, like I am profiling only DataAccess component and I am not profiling DataAccess.Test application. And no need to specify

the filters to remove System and NUnit type of assemblies.

Open cover generate results as XML files and with the help of Report Generator application you can view the coverage details.

And here is the syntax to get the details using Report Generator.

ReportGenerator.exe" coverage.xml "C:\Study\CodeCoverage\"

And here is the report generated using ReportGenerator summary and next is the detailed report.

Code coverage summary

Code coverage summary

And next is the detailed report.

Detailed Coverage details

Detailed Coverage details

Happy Code coverage :)

How measure get code coverage by PartCover with MSTest

If you are using VS 2010 Premium or Ultimate, you can get the code coverage from VS itself (You can find more posts related to code coverage here.). But if you are using Professional or less, you won’t get this code coverage feature. From last few months I am using VS Pro edition, and some time breaking the CI build because of low code coverage of my class. Today I found an alternative, PartCover 4.0 which helps to measure code coverage. You can download PartCover 4.0 . Installation is pretty easy, like any other software, and it has two parts UI version and command line version. I this post I am talking about UI version, which is called Part Cover browser.

  1. Open the Part cover browser, it will be displayed like this.
    Part Cover Browser

    Part Cover Browser

  2. Select File menu and click on the Run Target menu. It will popup a Window like this.
    Run target settings

    Run target settings


    In the window,

    1. Executable File : It the application required to run unit tests, in this case it MSTest.exe, normally which will be available in C:\Program Files\Microsoft Visual Studio 10.0\Common7\IDE\ location.
    2. Working Directory : After choosing the Executable file, Part cover automatically fill this location, by the same location of Executable, but you may need to change it and select the location, where your assemblies created.
    3. Working Arguments : This entry is required if you want to pass any parameters to the unit test engine as command line argument. For MS Test, it will be “/noisolation /testcontainer:YOUR UNIT TEST ASSEMBLY.” If you are using NUnit it will bedifferent.
    4. Rules : And the next and most important thing is Rules, which helps Part cover to give you coverage metrics for the specified assembly. If you want to get coverage of a assembly by including it and you can remove coverage by excluding it, it can be done using + and – signs respectively. Here is an example. Ignore namespaces, start with Microsoft.TeamFoundation and Microsoft.VisualStudio – -[Microsoft.TeamFoundation.*]* or -[Microsoft.VisualStudio.*]*
      And to include namespaces start with MySampleApp. +[MySampleApp.*]*. Or you cover all using +[*].
    5. Now click on the Start button, you can see two command line windows running and after few seconds it will display code coverage in the left side Treeview like this. Goto the View menu and select View coverage details, it will display the source code, with code coverage information, like this.
      Part cover with Code coverage results

      Part cover with Code coverage results

You can save the configuration, for future purposes and load it before starting code coverage. Here is the code and test class files.

Source code

public class UserRepository
{
    private Dictionary<string, string> _users = new Dictionary<string,string>();

    public void AddUser(string name, string address)
    {
        if (_users.ContainsKey(name))
        {
            throw new Exception("User already exists");
        }
        _users.Add(name, address);
    }

    public string GetAddress(string name)
    {
        if (!_users.ContainsKey(name))
        {
            throw new Exception("User not exists");
        }
        return _users[name];
    }
}

And here is the unit test

[TestClass]
public class UserRepositoryTest
{
    private UserRepository _testObject;

    [TestInitialize]
    public void Setup()
    {
        _testObject = new UserRepository();
    }

    [TestMethod]
    public void TestAddUser()
    {
        string expectedUser = "anuraj";
        string expectedAddress = "anuraj's address";
        _testObject.AddUser(expectedUser, expectedAddress);

        string actualAddress = _testObject.GetAddress(expectedUser);
        Assert.AreEqual(expectedAddress, actualAddress);
    }

    [TestMethod]
    [ExpectedException(typeof(Exception))]
    public void TestAddUserWithExistingUsername()
    {
        string expectedUser = "anuraj";
        string expectedAddress = "anuraj's address";
        _testObject.AddUser(expectedUser, expectedAddress);

        _testObject.AddUser(expectedUser, expectedAddress);
    }
}

Happy coding. :)

WCF Callbacks – A quick introduction

WCF callbacks are an old topic, but recently I got a chance to play around it. WCF callback means instead of normal request – response pattern, it will be a bidirectional communication between client and server.

First need to create the service interface

[ServiceContract(CallbackContract = typeof(IServiceCallback),
Namespace = "http://dotnetthoughts.net/wcf")]
interface IService
{
    [OperationContract(IsOneWay = true)]
    void SayHello(string name);
}

If you notice the Service contract attribute, there is parameter, Callback contract, which is required to map the service call with the callback method. And here is the callback contract interface.

interface IServiceCallback
{
    [OperationContract(IsOneWay = true)]
    void Print(string message);
}

And here is the implementation of the service and callback interface.

class Service : IService
{
    public void SayHello(string name)
    {
        IServiceCallback callback =
            OperationContext.Current.GetCallbackChannel<IServiceCallback>();
        string message = string.Format("Hello {0}", name);
        callback.Print(message);
    }
}

class ServiceCallback : IServiceCallback
{
    public void Print(string message)
    {
        Console.WriteLine(message);
    }
}

I am using Self Hosting mode to host the service. And here is the implementation.

class Program
{
    static void Main(string[] args)
    {
        string baseAddress = "net.tcp://localhost:8080/";
        Uri[] addresses = { new Uri(baseAddress) };
        using (var serviceHost = new ServiceHost(typeof(Service), addresses))
        {
            serviceHost.AddServiceEndpoint(typeof(IService),
                new NetTcpBinding(), "IService");

            serviceHost.Open();
            Console.WriteLine("Service started.");
            Console.WriteLine("Press any key to stop.");
            Console.ReadKey(true);
            serviceHost.Close();
        }
    }
}

Now we need to create proxy to communicate to our service. Here is the proxy implementation.

class ServiceProxy : DuplexClientBase<IService>, IService
{
    public ServiceProxy(object callbackInstance,
        Binding binding, EndpointAddress remoteAddress)
        : base(callbackInstance, binding, remoteAddress)
    {

    }
    public void SayHello(string name)
    {
        Channel.SayHello(name);
    }
}

And finally here is the client implementation, in the client class; I am implementing the callback interface, so that I can get the callback result in the client.

class Client : IServiceCallback
{
    public void SayHelloToService(string name)
    {
        var proxy =
            new ServiceProxy(this, new NetTcpBinding(),
                new EndpointAddress("net.tcp://localhost:8080/IService"));
        proxy.SayHello(name);
    }

    public void Print(string message)
    {
        Console.WriteLine(message);
    }
}

Now start the Service first then create the instance of client class and invoke SayHelloToService with name parameter and it will be printed in the console. And here is the Test for the same.


[TestClass]
public class TestService : IServiceCallback
{
    private string actual = string.Empty;
    private AutoResetEvent autoResetEvent = null;
    [TestMethod]
    public void TestSayHello()
    {
        string expected = "Hello dotnetthoughts";
        autoResetEvent = new AutoResetEvent(false);
        var proxy =
            new ServiceProxy(this, new NetTcpBinding(),
                new EndpointAddress("net.tcp://localhost:8080/IService"));
        proxy.SayHello("dotnetthoughts");
        Assert.IsTrue(autoResetEvent.WaitOne(5000), @"Callback not recevied.");
        Assert.IsTrue(expected == actual, @"Invalid response from callback.");
    }

    public void Print(string message)
    {
        actual = message;
        autoResetEvent.Set();
    }
}

Happy Coding :)

Unit Test Adapter threw exception – Unable to load one or more of the requested types

Today evening while working(?) around unit tests and code coverage, I got an exception from Visual Studio 2010. I wrote two unit test cases and it was passing, then I enabled code coverage in my solution, and the passing unit tests started failing. And I am getting error message like Unit Test Adapter threw exception: Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information. from Test results window. :( Initially I thought Microsoft PEX is the culprit ;) I searched for the solution and found few solutions;like Clean and Build, but it didn’t worked for me. From another blog I found some other solution like to modify the vsmdi file. But I didn’t tried that option. Later I come to know, I forgot to disable the signing of the assemblies. You can do this selecting Project Properties > Signing > Un-check the sign assembly checkbox. I disabled the signing in the assemblies and it started working. :D

Happy unit testing :)

Quick introduction to MS Test

Recently I started using MS Test, moved from NUnit tests to MS Test. Mainly the reason for adopting MS Test is the ability to measure code coverage from Visual Studio itself. In this post I am quickly introducing MS Test for developers.

  1. Created a class library – SampleCalcLib. And added a class file, which do two mathematical operations Addition and Division.
  2. using System;
    namespace SampleCalcLib
    {
        public class CalcLib
        {
            public int Addition(int a, int b)
            {
                return a + b;
            }
    
            public int Division(int a, int b)
            {
                if (b == 0)
                {
                    throw new DivideByZeroException();
                }
                return a / b;
            }
        }
    }
    
  3. Created a Test Project. – SampleCalcTest – This project contains the Test methods verify the Addition and Division methods.
  4. using System;
    using Microsoft.VisualStudio.TestTools.UnitTesting;
    using SampleCalcLib;
    namespace SampleCalcTest
    {
        [TestClass]
        public class CalcLibTest
        {
            [TestMethod]
            public void TestAddition()
            {
                CalcLib calcLib = new CalcLib();
                int a = 10;
                int b = 20;
                int actual = a + b;
                int expected = calcLib.Addition(a, b);
                Assert.AreEqual(expected, actual);
            }
    
            [TestMethod]
            public void TestDivision()
            {
                CalcLib calcLib = new CalcLib();
                int a = 10;
                int b = 20;
                int actual = a / b;
                int expected = calcLib.Division(a, b);
                Assert.AreEqual(expected, actual);
            }
    
            [TestMethod]
            [ExpectedException(typeof(DivideByZeroException))]
            public void TestDivisionExpectingDivideByZeroExecption()
            {
                CalcLib calcLib = new CalcLib();
                int a = 10;
                int b = 0;
                int expected = calcLib.Division(a, b);
            }
        }
    }
    
  5. Now the solution explorer will look like the following.
  6. Solution Explorer

    Solution Explorer

  7. We can also right click on a method and select Create Unit Test option, which will create test project and add test method to it.
  8. You can find all the tests in the test project using Test View window. You can get Test View from Test menu Windows and then select Test View.
  9. Test View window

    Test View window

  10. To Run the test by right clicking on the project in the Test View window.
  11. You can view the Test Results from Test Results window.
  12. Test Results

    Test Results

I will post how to enable and view code coverage in the next post

« Newer PostsOlder Posts »