Integration Testing for Microservices

In the previous lesson we have written unit tests for ProductService, and we validated its method output by using fake objects. It was fairly simple. Now, let us learn how to test the methods or code blocks that integrate one or more modules/blocks. To do this, we need to learn about integration tests.

Add a new project and subsequent test classes. Follow the below steps:

  1. Right-click on Solution, and then click Add Project.
  2. From the Add a new project window, select XUnit Test Project (.NET Core).
  3. Provide a meaningful name.
  1. Add the appsettings.json file, and then add the following code to it:
 {
   "ConnectionStrings": 
   {
     "ProductConnection": "Data Source=.;Initial
     Catalog=ProductsDB;Integrated
     Security=True;MultipleActiveResultSets=True"
   },
   "buildOptions": 
   {
     "copyToOutput": 
     {
       "include": [ "appsettings.json" ]
     }
   }
 } 
  1. Open the Startup.cs file, of the Sportopia.SportsStore.ProductService project.
  2. Now, let’s make the ConfigureServices and Configure methods void. We’re doing this so that we can override these methods in our TestStartup.cs class. These methods will look as follows:
public virtual void ConfigureServices(IServiceCollection services)
{
   services.AddTransient<IProductRepository,
   ProductRepository>();
   services.AddDbContext<ProductContext>(
   o => o.UseSqlServer(Configuration.
   GetConnectionString("ProductConnection")));
   services.AddMvc();
   //Code ommited
}
public virtual void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
 if (env.IsDevelopment())
 {
 app.UseDeveloperExceptionPage();
 app.UseBrowserLink();
 }
 else
 {
 app.UseExceptionHandler("/Home/Error");
 }
 app.UseStaticFiles();
 app.UseMvc(routes =>
 {
 routes.MapRoute(name: "default",
 template: "{controller=Home}/{action=
 Index}/{id?}");
 });
 app.UseSwaggerUI(op =>
 {
 op.SwaggerEndpoint("/swagger/v1/swagger.json", 
 "Product API V1");
 });
}
  1. Add a new folder called Services.
  2. Add the TestStartup.cs class.
  3. Open NuGet Manager. Search for and add the Microsoft.AspNetCore.TestHost package
  1. Add the following code to TestStartup.cs:
public class TestStartup : Startup
{
   public TestStartup(IConfiguration 
   configuration) : base(configuration)
   { }
   public override void ConfigureServices
   (IServiceCollection services)
   {
   //mock context
   services.AddDbContext<ProductContext>(
   o => o.UseSqlServer(Configuration.
   GetConnectionString("ProductConnection")));
   services.AddMvc();
   }
 public override void Configure(IApplicationBuilder
 app, IHostingEnvironment env)
   { }
}
  1. Under the Services folder, add a new ProductTest.cs class, and then add the following code to it:
public class ProductTest
{
  public ProductTest()
  {
    // Arrange
    var webHostBuilder = new WebHostBuilder()
    .UseStartup<TestStartup>();
    var server = new TestServer(webHostBuilder);
    _client = server.CreateClient();
  }
  private readonly HttpClient _client;
  [Fact]
  public async Task ReturnProductList()
  {
    // Act
    var response = await _client.GetAsync
    ("api/product/productlist"); //change per //setting
    response.EnsureSuccessStatusCode();
    var responseString = await response.Content.
    ReadAsStringAsync();
    // Assert
    Assert.NotEmpty(responseString);
  }
}
  1. To verify these tests, right-click the solution, and then select Run tests (if you face NuGet package errors, make sure you restore all the packages).

Using the steps above we are checking a simple test. We are trying to verify the response of the service, by setting up a client with the use of HttpClient. The test will fail if the response is empty.

You might be interested in the following courses:

Course Category

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