Integration Testing in ASP.NET Core with Example – Part II

Today in this article we will see how to create Integration Testing in ASP.NET Core with Example.

In our last article, we looked at how to set up the Integration Test project in ASP.NET Core 3.1 using the XUnit framework.

Today we shall continue and write an Integration test for another scenario where our API communicates with Datastore i.e MongoDB

Today in this article, we will cover below aspects,

Integration Testing is one of the XP practices of software development where features are developed iteratively with a small quantity tested for their integration with other components.

IntegrationTest DownStream- API and Database

We shall be doing the Integration test between and database connectivity so that we verify the Integration between Service and its Downstream components. You could have single or multiple downstream connectivities.

Integration Testing in ASPNET Core with Example

Let’s see more details on the concept as below.

As shown in the above diagram,

  • Service A is a new service in the development and has a dependency on the Database i.e MongoDB.
  • Here Integration Testing will make sure,
    • Tests are written for endpoints of ServiceA i.e GET, PUT, POST or DELETE.
    • Connection with ServiceA and database is established successfully. i.e this test will validate your connection string includes database host and name and credentials.
    • Two independent Components like ServiceA and Databases communicate with each other.
    • Basic CRUD operations are successful.
    • Proper HTTP responses are sent to the consumers (who are consuming Service A and making sure that the contract is obeyed as per the specification)
    • Any breaking changes introduced in any form will get caught by Integration Tests ensuring appropriate action.

Below is a simple GET API example that connects to the MongoDB database and fetches the result.

For a complete example – please visit this article.

        [HttpGet("{id}")]
        public ActionResult Get(int? id)
        {
            if (!id.HasValue)
            {
               return BadRequest(ModelState);
            }

            return Ok(_employeeRepository.GetEmployeeByID(id));
        }

So here there are two components that are interacting meet each other including API and datastore that is MongoDB.

Let’s create a Test Project and name it as BooksService.Integration.Tests.

Please add a TestClass named as BooksServiceIntegrationTests

 public class BooksServiceIntegrationTests : IClassFixture<AppTestFixture>
    {
        readonly AppTestFixture _fixture;
        readonly HttpClient _client;
        public BooksServiceIntegrationTests(AppTestFixture fixture)
        {
            _fixture = fixture;
            _client = _fixture.CreateClient();
        }
    ..
}

Please note that when the constructor executes it uses AppTestFixture which in turn launches WebApplicationFactory which bootstraps an application in memory.

AppTestFixture class is defined as below,

public class AppTestFixture : WebApplicationFactory<Startup>
    {
        //override methods here as needed
    }

Here AppTestFixture uses the Startup class to lanch in-memory instance of the Target service.

So we are done with Test Host setup and provision to create a client against that server.

Let’s now see how to create integration tests and perform testing,

        [Fact]
        public async Task GET_GetBookListAll_Valid_Input_Success()
        {
            //Arrange
            string employeeNumber = "1234";
                
            // Act
            var response = await _client.GetAsync($"/api/employee/{employeeNumber}");

            var result =  response.Content.ReadAsStringAsync().Result;
          
            // Assert1
            Assert.Equal(HttpStatusCode.OK, response.StatusCode);
            // Assert2
            Assert.Equal("application/json; charset=utf-8",
                response.Content.Headers.ContentType.ToString());
        }

Integration Testing in ASPNET Core with Example

Above, finally, we are achieving below,

  • Making sure Database connections are established.
  • We are also making sure the API/Services returns the proper HTTP Status code to its consumer

IntegrationTest Upstream- API and Service

In the above example, we looked at how to perform Integration Between Target Service development (Software Under Test) and downstream components.

Please see the below article for the Upstream and API Contract testing approach discussed.

Integration Testing in ASPNET Core with Example

That’s All. Happy Coding !!



Please bookmark this page and share it with your friends. Please Subscribe to the blog to receive notifications on freshly published(2024) best practices and guidelines for software design and development.



Leave a Reply

Your email address will not be published. Required fields are marked *