Testing A Microservice Application

Testing a microservice could be a bit challenging. The following reasons explain why it could be a complex task:

  1. Microservices may have multiple services that work together or individually for an enterprise system.
  2. Often times microservices are meant to target multiple clients, so they involve more complex use cases.
  3. Each component/service of the microservice architectural style is isolated and independent, so they need to be tested both individually and as a complete system.
  4. There may be independent teams working on separate components/services that may be required to interact with each other. Therefore, tests should cover not only internal services but also external services.
  5. Each component/service in a microservice is designed to work independently, but they may have to access common/shared data, where each service is responsible for modifying its own database. Services need to access data using API calls to other services, which adds further dependencies to other services. This type of testing will have to be handled using mock tests.

Microsoft Unit Testing Framework

Microsoft Unit Testing Framework provides a facility to test individual operations of independent components. To ensure that all the tests pass and that any new functionality or changes don’t break anything (if any functionality breaks down, then the related unit test will fail), these tests can be run on every compilation of the code.

To make sure that responses are consistent with the expectations of the clients or consumers, consumer-driven contract testing can be used. Services use data from an external party or from other services, and they can be tested by setting up the endpoint of the services that are responsible for handling the data. By doing this, we can use a mocking framework or library, such as Moq, to mock these endpoints during the integration process.

Creating The Test Project

Prerequisites:

  1. Visual Studio 2019
  2. .NET Core 3.1
  3. C# 8.0
  4. xUnit and MS tests
  5. The Moq framework 

We will write tests for the application that we created in one of the previous lessons. https://geekhours.com/375/lesson/building-a-microservice-using-c-sharp-asp-dot-net-core-mvc-entity-framework/

From the Solution Explorer, within Using Visual Studio, right-click on Solution and click Add | New Project, as shown in the following screenshot:

Microsoft Unit Testing Framework new project

From the Add, a new project template, select xUnit Test Project (.NET Core), and provide a meaningful name, for example, Sportopia.SportsStore.ProductService.UnitTests:

xUnit Test Project

Once the project is created, let’s move on to test ProductService, to make sure that our service returns product data without failure. We will use fake objects to achieve that. Follow the steps below:

  1. Delete the default UniTest1.cs file from your test project.
  2. Add a new folder, and then name it Fake in the Sportopia.SportsStore.ProductService.UnitTests project.
  3. Under the Fake folder, add the ProductData.cs class, and then add the following code. The code snippet is basically creating fake data of the ProductViewModel type.
 public IEnumerable<ProductViewModel> GetProducts()
  {
    var productVm = new List<ProductViewModel>
    {
      new ProductViewModel
      {
        CategoryId = Guid.NewGuid(),
        CategoryDescription = "Category Description",
        CategoryName = "Category Name",
        ProductDescription = "Product Description",
        ProductId = Guid.NewGuid(),
        ProductImage = "Image full path",
        ProductName = "Product Name",
        ProductPrice = 112M
      },
      new ProductViewModel
      {
        CategoryId = Guid.NewGuid(),
        CategoryDescription = "Category Description-01",
        CategoryName = "Category Name-01",
        ProductDescription = "Product Description-01",
        ProductId = Guid.NewGuid(),
        ProductImage = "Image full path",
        ProductName = "Product Name-01",
        ProductPrice = 12M
      }
    };
    return productVm;
  }

Next, we create fake data by making two lists of ProductViewModel and Product. These lists contain fake data to test the output of ProductViewModel and Product.

 public IEnumerable<Product> GetProductList()
  {
    return new List<Product>
    {
      new Product
      {
        Category = new Category(),
        CategoryId = Guid.NewGuid(),
        Description = "Product Description-01",
        Id = Guid.NewGuid(),
        Image = "image full path",
        Name = "Product Name-01",
        Price = 12M
      },
      new Product
      {
        Category = new Category(),
        CategoryId = Guid.NewGuid(),
        Description = "Product Description-02",
        Id = Guid.NewGuid(),
        Image = "image full path",
        Name = "Product Name-02",
        Price = 125M
      }
    };
  }
  1. Add the Services folder to the Sportopia.SportsStore.ProductService.UnitTests project.
  2. Under the Services folder, add the ProductTests.cs class.
  3. Open NuGet Manager, and then search for and add moq, as shown in the following screenshot:
moq-unit-testing-microservices
  1. Add the following code to the ProductTests.cs class.
public class ProductTests
{
    [Fact]
    public void Get_Returns_ActionResults()
    {
      // Arrange
      var mockRepo = new Mock<IProductRepository>();
      mockRepo.Setup(repo => repo.GetAll()).
      Returns(new ProductData().GetProductList());
      var controller = new ProductController(mockRepo.Object);
      // Act
      var result = controller.GetList();
      // Assert
      var viewResult = Assert.IsType<OkObjectResult>(result);
      var model = Assert.IsAssignableFrom<IEnumerable<
      ProductViewModel>>(viewResult.Value);
      Assert.NotNull(model);
      Assert.Equal(2, model.Count());
    }
}

Using the above code, we are mocking our repository and testing the output of our Web API controller. This test is based on the AAA technique; it will be passed if you meet the mocked data during setup.

You might be interested in the following courses:

Course Category

Back to: Microservices with C#, .NET Core and Azure > Testing