Implementing Unit testing using xUnit.Net

|  Posted: February 2, 2017  |  Categories: General Technical
Tags: .NET General

Unit Testing

Unit testing is a software development process in which the smallest testable parts of an application, called units, are individually and independently scrutinized for proper operation. Unit testing is often automated but it can also be done manually.

Test-Driven Development (TDD) is a development technique where you must first write a test that fails, before you write new functional code. TDD is being quickly adopted by agile software developers for development of application source code and is even being adopted by Agile DBAs for database development.

.NET code unit testing with xUnit.net

xUnit.net is a free, open source, community-focused unit testing tool for the .NET Framework. Written by the original inventor of NUnit v2, xUnit.net is the latest technology for unit testing C#, F#, VB.NET and other .NET languages. xUnit.net works with ReSharper, CodeRush, TestDriven.NET and Xamarin. It is part of the .NET Foundation, and operates under their code of conduct. It is licensed under Apache 2 (an OSI approved license).

Create a Unit Test Project

Let’s start by creating a Unit Test Project.

Open Visual Studio and Create->New->Unit Test Project

New Unit Test Project

Add a Reference to xUnit.net

  1. In the Solution Explorer, right click the new project and Choose “Manage NuGet Packages
  2. Now in NuGet Package Manager window,
    1. On the right upper corner, ensure nuget.org is selected
    2. In the search box, type “unit in browse mode”
    3. Install xUnit.net

By installing the xUnit.net, we can get references to all other packages. it brings packages that include Core unit testing framework and assertion framework.

Installing xUnit.net

Add reference to xunit.runner.console

The steps to add a reference to xunit.runner.console are the same as for the previous installation. Choose xunit.runner.console and install the package.

Unlike the previous package, this package is what’s known as a solution-level package. Instead of having assemblies to reference, it adds some tools in the solution folder. We will use one of these tools-console runner-to run the tests.

­­

Add reference to xunit.runner.console

Add Reference to xunit.runner.visualstudio

The steps to add a reference to xunit.runner.visualstudio are also the same as the previous installations. Let’s now install that xunit.runner.visualstudio package. It associates the test results with VS Test Explorer.

Add Reference to xunit.runner.visualstudio

Simple Unit Test

When you create the project, Visual Studio automatically creates the UnitTest1.cs.

  1. Here, we have written a single unit test and built a solution to ensure that the code compiles
  2. To run the test, right click the [Fact] and choose run test. Before that ensure test explorer is visible (Go to Test->Windows->Test Explorer)
namespace UnitTestPractice.UnitTest
{
  public class UnitTest1
  {
    [Fact]
    public void TestMethod1()
    {
      Assert.Equal(3, Add(2, 1));
    }

    private int Add(int a, int b)
    {
      return a + b;
    }
  }
}

Simple Unit Test

Advanced Unit Test

Create a ASP.NET web Application. Right click the Solution Explorer; File->New->Project->Web->ASP.NET web Application

Advanced Unit Test

Here, we have written a unit test for ValuesController. For that we have to create a Service for ValuesController. Right click web application Add ->New Folder, and name it as “Service”.

Service for ValuesController

­­­­

Right click the Service Folder; Add->Class->Interface

Add Interface

Interface added to Service

Next, we will create the class Service and implement the methods in the IValuableInterface.

using System.Collections.Generic;

namespace UnitTestPractice.Service
  {
    public interface IValueService
    {
      IEnumerable<string>GetAllValues();
string GetAllValue(int id);
    }

  public class Service : IValueService
  {
    public IEnumerable<string>GetAllValues()
    {
      return new string[] { "value1", "value2" };
    }
    public string GetAllValue(int id)
    {
      return "value";
    }
  }
}

The ValuesController will be like this –

using System.Collections.Generic;
using System.Web.Http;
using UnitTestPractice.Service;

namespace UnitTestPractice.Controllers
  {
  public class ValuesController : ApiController
    {
      private readonly IValueService _valueservice;

      public ValuesController(IValuableService valueservice)
      {
        this._valueservice = valueservice;
      }

      public IEnumerable<string>Get()
      {
        return this._valueservice.GetAllValues();
      }

      public string Get(int id)
      {
        return this._valueservice.GetAllValue(id);
      }
   }
}

In this ValuesController, we created a Private object for the IValuableInterface and using that object to call the methods in the Service class.

Next, we have to add the reference for the Unit Test Project. Right-click Web Application, Add->Reference. Refer to the unit test project.

Refer unit test project

Adding Moq

Navigate to NuGet Gallery and browse for the Moq package and install the Moq version 4.5.28.

Mocking is primarily used in unit testing. An object under test may have dependencies on other objects. To isolate the behaviour of the object you want to test, you replace the other objects by mocks that simulate the behavior of the real objects. This is useful if the real objects are impractical to incorporate into unit tests.

NuGet Package Manager

In the UnitTest class we have written the Test Methods for ValuesController,

using Moq;
using System.Linq;
using UnitTestPractice.Controllers;
using UnitTestPractice.Service;
using Xunit;

namespace UnitTestPractice.UnitTest
{
  public class UnitTest1
  {
    [Fact]
    public void TestMethod1()
      {
        var valueServiceMock = new Mock<IValuableService>();
        valueServiceMock.Setup(service => service.GetAllValues())
.Returns(new[] { "value1", "value2" });
        var controller = new ValuesController(valueServiceMock.Object);
        var values = controller.Get();
        var results = values.ToArray();
        Assert.Equal(2, results.Length);
        Assert.Equal("value1", results[0]);
        Assert.Equal("value2", results[1]);
      }

     [Fact]
     public void TestMethod2()
     {
       var valueServiceMock = new Mock<IValuableService>();
       valueServiceMock.Setup(service => service.GetAllValue(1))
.Returns("value");
       ValuesController controller = new ValuesController(valueServiceMock.Object);
       var values = controller.Get(1);

       Assert.Equal(values, "value");
     }
  }
}

In Test Explorer, click Run All

RunAll

All Tests have successfully passed. In Test Explorer, you can also check the time taken to execute the tests.  In our example its 4ms and 1 second. With this execution time information, developers can later decide if performance tuning is needed.

Author: Yuvaranjani Kalichamy

Software Engineer Trainee,BizTalk360

One Platform Operations, Monitoring and Analytics Software
BizTalk360

microsoft biztalk

Learn more

Over 500 customers across 30+ countries depend on BizTalk360

ServiceBus360

Azure Composite Application

Learn more

Start manage and monitor your Azure Services in minutes

One Platform - Operations, Monitoring and Analytics Software
BizTalk360

microsoft biztalk

Learn more

Over 500 customers across 30+ countries depend on BizTalk360

One Platform - Operations, Monitoring and Analytics Software
ServiceBus360

Azure Composite Application

Learn more

Start manage and monitor your Azure Services in minutes

Back to Top