Mocking with Moq in C# :👈 👉:Test-Driven Development (TDD)

Integration and Load Testing in ASP.NET Core

🧪Integration and Load Testing in ASP.NET Core

🔗 Integration Testing

Integration testing ensures that different modules or services in a system work together as expected. It is typically performed after unit testing and before system testing.

✅ Purpose

  • Validate data flow between modules
  • Detect interface mismatches and contract violations
  • Ensure modules integrate correctly in real-world scenarios

🧪 Types

  • Big Bang Integration: All components are integrated at once and tested together
  • Incremental Integration: Modules are integrated and tested step-by-step
    • Top-down: Start from top-level modules
    • Bottom-up: Start from lower-level modules
    • Sandwich: Mix of top-down and bottom-up

1. What Is Integration Testing?

Integration testing verifies whether multiple parts of an application work correctly together.

In ASP.NET Core, an integration test can verify the interaction between:

  • Controllers and services.
  • Middleware and routing.
  • Dependency injection.
  • Authentication and authorization.
  • Entity Framework Core and databases.
  • Web APIs and external dependencies.

Example: When a client sends a POST request to create a product, an integration test checks whether the request reaches the correct endpoint, passes through middleware, executes business logic, saves the product and returns the expected HTTP response.

Unit Testing vs Integration Testing

Unit TestingIntegration Testing
Tests a single method or component.Tests multiple components working together.
Dependencies are usually mocked.Real application components are commonly used.
Executes very quickly.Usually takes longer.
Finds logic-level defects.Finds communication and configuration defects.
Example: Test a calculation method.Example: Test an API endpoint with a database.

2. Why Is Integration Testing Important?

Consider an ASP.NET Core application with this architecture:

Client ProductsController ProductService ProductRepository SQL Server

Each component may pass its individual unit tests, but the complete flow can still fail because of:

  • Incorrect dependency injection registration.
  • Incorrect route configuration.
  • Database connection problems.
  • Serialization or deserialization issues.
  • Middleware configuration errors.
  • Authentication and authorization problems.
  • Incorrect HTTP status codes.

Integration testing helps identify these problems before deployment.

3. Tools Used for Integration Testing

ToolPurpose
xUnitTesting framework.
NUnitAlternative testing framework.
MSTestMicrosoft's testing framework.
Microsoft.AspNetCore.Mvc.TestingProvides ASP.NET Core integration testing support.
WebApplicationFactoryCreates an in-memory test server for the application.
TestServerHosts the application for integration tests.
EF Core InMemoryLightweight in-memory database provider.
SQLite In-MemoryRelational database testing with an in-memory database.
TestcontainersRuns real dependencies such as SQL Server or PostgreSQL in containers.

4. Integration Testing Using WebApplicationFactory

ASP.NET Core provides WebApplicationFactory<TEntryPoint> through the Microsoft.AspNetCore.Mvc.Testing package.

It allows tests to start the application in a test environment and send HTTP requests without deploying the application to a real web server.

Step 1: Create an ASP.NET Core API

Example model:

public class Product
{
    public int Id { get; set; }
    public string Name { get; set; } = string.Empty;
    public decimal Price { get; set; }
}

Example controller:

[ApiController]
[Route("api/products")]
public class ProductsController : ControllerBase
{
    private readonly AppDbContext _context;
    public ProductsController(AppDbContext context)
    {
        _context = context;
    }
    [HttpGet]
    public async Task<IActionResult> GetProducts()
    {
        var products = await _context.Products.ToListAsync();
        return Ok(products);
    }
    [HttpPost]
    public async Task<IActionResult> CreateProduct(Product product)
    {
        _context.Products.Add(product);
        await _context.SaveChangesAsync();
        return CreatedAtAction(
            nameof(GetProducts),
            new { id = product.Id },
            product);
    }
}

Step 2: Install Required Packages

Install these packages in the test project:

dotnet add package Microsoft.AspNetCore.Mvc.Testing
dotnet add package Microsoft.EntityFrameworkCore.Sqlite
dotnet add package xunit
dotnet add package xunit.runner.visualstudio

Use package versions compatible with your application's target .NET version.

Step 3: Create a Custom WebApplicationFactory

The factory allows us to replace the production database configuration with a test database.

public class CustomWebApplicationFactory
    : WebApplicationFactory<Program>
{
    private SqliteConnection? _connection;
    protected override void ConfigureWebHost(
        IWebHostBuilder builder)
    {
        builder.ConfigureServices(services =>
        {
            var descriptor = services.SingleOrDefault(
                d => d.ServiceType == typeof(DbContextOptions<AppDbContext>));
            if (descriptor != null)
            {
                services.Remove(descriptor);
            }
            _connection = new SqliteConnection("DataSource=:memory:");
            _connection.Open();
            services.AddDbContext<AppDbContext>(options =>
            {
                options.UseSqlite(_connection);
            });
            var serviceProvider = services.BuildServiceProvider();
            using var scope = serviceProvider.CreateScope();
            var db = scope.ServiceProvider
                .GetRequiredService<AppDbContext>();
            db.Database.EnsureCreated();
        });
    }
    protected override void Dispose(bool disposing)
    {
        base.Dispose(disposing);
        if (disposing)
        {
            _connection?.Dispose();
        }
    }
}

Important: For this example, expose the application entry point to the test project. With top-level statements, you can add this at the end of Program.cs:

public partial class Program { }

The SQLite connection remains open for the lifetime of the factory because an in-memory SQLite database is tied to its connection.

Step 4: Write an Integration Test

public class ProductsIntegrationTests
    : IClassFixture<CustomWebApplicationFactory>
{
    private readonly HttpClient _client;
    public ProductsIntegrationTests(
        CustomWebApplicationFactory factory)
    {
        _client = factory.CreateClient();
    }
    [Fact]
    public async Task GetProducts_ReturnsSuccessStatusCode()
    {
        // Act
        var response = await _client.GetAsync("/api/products");
        // Assert
        response.EnsureSuccessStatusCode();
        Assert.Equal(
            HttpStatusCode.OK,
            response.StatusCode);
    }
    [Fact]
    public async Task CreateProduct_ReturnsCreatedStatusCode()
    {
        // Arrange
        var product = new
        {
            Name = "Laptop",
            Price = 50000
        };
        // Act
        var response = await _client.PostAsJsonAsync(
            "/api/products",
            product);
        // Assert
        Assert.Equal(
            HttpStatusCode.Created,
            response.StatusCode);
    }
}

What Happens During This Test?

  1. WebApplicationFactory starts the ASP.NET Core application.
  2. The application uses the test database configuration.
  3. CreateClient() creates an HTTP client for the test server.
  4. The test sends an actual HTTP request through the application pipeline.
  5. The controller and database operations execute.
  6. The test verifies the returned HTTP response.

This tests more than calling a controller method directly.

Note: The example demonstrates the testing setup. For reliable independent tests, create a fresh database or clean the database state before each test. Also, seed data when testing scenarios that require existing records.

5. What Should You Test in ASP.NET Core Integration Tests?

API Endpoints

  • GET returns the expected data.
  • POST creates a record.
  • PUT updates an existing record.
  • DELETE removes a record.
  • Invalid requests return appropriate status codes.

Authentication and Authorization

  • Unauthenticated requests return 401 Unauthorized when authentication is required.
  • Authenticated users can access permitted endpoints.
  • Users without the required permissions receive 403 Forbidden.

Database Integration

  • Data is saved correctly.
  • Data can be retrieved correctly.
  • Transactions behave as expected.
  • Constraints and relationships work correctly.

Middleware

  • Exception-handling middleware works.
  • Logging middleware executes.
  • CORS configuration behaves as expected.
  • Request validation works.

Error Handling

  • Invalid input returns 400 Bad Request.
  • Missing resources return 404 Not Found.
  • Unexpected errors are handled appropriately.

6. What Is Load Testing?

⚙️ Load Testing

Load testing evaluates how a system performs under expected and peak user loads. It helps identify performance bottlenecks and ensures scalability.

✅ Purpose

  • Measure system responsiveness and stability
  • Identify performance bottlenecks
  • Ensure system can handle expected traffic

🧪 Types

  • Baseline Load Testing: Normal expected usage
  • Stress Testing: Beyond maximum capacity
  • Spike Testing: Sudden increase in load
  • Soak Testing: Sustained load over time

Load testing measures how an application performs when multiple users or requests access it simultaneously.

It helps determine whether the application can handle its expected workload.

For example, imagine an ASP.NET Core API used by an e-commerce website.

During normal usage:

  • 100 users access the application.
  • 50 users search for products.
  • 30 users view product details.
  • 20 users place orders.

During a promotional sale, the number of concurrent users may increase significantly.

Load testing helps determine whether the application can handle this traffic while maintaining acceptable response times and reliability.

7. Why Is Load Testing Required?

Without load testing, an application may work perfectly during development but fail under real-world traffic.

Common problems include:

  • Slow API responses.
  • High CPU utilization.
  • High memory consumption.
  • Database connection pool exhaustion.
  • Thread pool starvation.
  • Too many database queries.
  • HTTP request timeouts.
  • Increased error rates.
  • Application crashes under heavy traffic.

Load testing helps identify performance bottlenecks before production deployment.

8. Types of Performance Testing

Testing TypePurpose
Load TestingChecks performance under expected user traffic.
Stress TestingChecks how the application behaves beyond expected capacity.
Spike TestingChecks how the application handles sudden traffic increases.
Endurance TestingChecks stability during prolonged workloads.
Scalability TestingChecks how performance changes as resources or traffic increase.
Volume TestingChecks performance when handling large amounts of data.

Example

Suppose an API is expected to support 1,000 concurrent users.

  • Load testing: Test the expected workload.
  • Stress testing: Gradually increase traffic beyond the expected workload.
  • Spike testing: Suddenly increase traffic from a low level to a high level.
  • Endurance testing: Maintain a representative workload for several hours.

9. Tools Used for Load Testing

ToolDescription
k6Developer-friendly load testing tool with JavaScript-based test scripts.
Apache JMeterPopular open-source performance testing tool with a graphical interface.
Azure Load TestingManaged load testing service on Azure.
GatlingLoad testing tool with code-based scenarios.
NBomber.NET-oriented load testing and performance testing framework.

For ASP.NET Core applications, k6 and NBomber are useful options. Azure Load Testing is useful when running managed load tests in Azure.

10. Load Testing Using k6

k6 allows us to simulate multiple virtual users sending requests to an API.

Step 1: Create a k6 Test Script

Create a file named load-test.js.

import http from 'k6/http';
import { check, sleep } from 'k6';
export const options = {
    vus: 50,
    duration: '1m',
};
export default function () {
    const response = http.get(
        'https://localhost:7001/api/products'
    );
    check(response, {
        'status is 200': (r) => r.status === 200,
        'response time below 500ms': (r) => r.timings.duration < 500,
    });
    sleep(1);
}

Step 2: Run the Test

k6 run load-test.js

Explanation

  • vus: 50 means 50 virtual users.
  • duration: '1m' means the test runs for one minute.
  • http.get() sends an HTTP GET request.
  • check() verifies the response status and response time.
  • sleep(1) adds a one-second pause between iterations for each virtual user.

Important: Virtual users are simulated execution loops, not necessarily 50 requests per second. The actual request rate depends on response time, script execution and the configured sleep interval.

For local HTTPS testing, configure certificate trust appropriately rather than disabling TLS verification in a real performance test.

11. Understanding Important Load Testing Metrics

These are the most important metrics to monitor.

1. Response Time

The time taken by the server to respond to a request.

Average Response Time = 250 ms

A lower response time is generally better, but always consider the API's business requirements.

2. Throughput

The number of requests processed in a given period.

Throughput = 500 requests per second

Higher throughput generally indicates that the application can process more requests, provided response times and error rates remain acceptable.

3. Concurrent Users

The number of users actively using the application at the same time.

Concurrent Users = 1,000

4. Error Rate

The percentage of requests that fail.

Error Rate (%) =
(Failed Requests / Total Requests) * 100

Example:

Total Requests  = 10,000
Failed Requests = 100
Error Rate = (100 / 10000) * 100
           = 1%

5. CPU Utilization

Indicates how much CPU capacity the application is consuming.

High CPU utilization may indicate:

  • Expensive calculations.
  • Inefficient code.
  • Excessive serialization.
  • High request volume.

6. Memory Utilization

Indicates how much memory the application consumes.

Watch for continuously increasing memory usage, excessive allocations and frequent garbage collection.

7. Percentile Response Times

Average response time alone does not show the complete picture.

MetricMeaning
p5050% of requests completed within this time.
p9090% of requests completed within this time.
p9595% of requests completed within this time.
p9999% of requests completed within this time.

Example:

p50 = 100 ms
p90 = 250 ms
p95 = 400 ms
p99 = 900 ms

This means 95% of requests completed within 400 ms, while the slowest 5% took longer.

12. How to Identify Performance Bottlenecks in ASP.NET Core

When a load test shows poor performance, investigate the application systematically.

Application-Level Issues

  • Avoid unnecessary object allocations.
  • Use asynchronous I/O operations.
  • Avoid blocking calls such as .Result and .Wait() in request-handling code.
  • Optimize expensive business logic.
  • Use pagination for large result sets.
  • Avoid unnecessary serialization and deserialization.

Database-Level Issues

  • Identify slow SQL queries.
  • Add appropriate indexes.
  • Avoid N+1 query problems.
  • Use connection pooling correctly.
  • Avoid loading unnecessary records.
  • Review transaction duration.

Infrastructure-Level Issues

  • Monitor CPU and memory.
  • Check network latency.
  • Review container resource limits.
  • Check database connection limits.
  • Review load balancer configuration.
  • Evaluate horizontal and vertical scaling.

13. Best Practices for Integration and Load Testing

Integration Testing Best Practices

  1. Test actual HTTP endpoints using WebApplicationFactory.
  2. Use a separate test database.
  3. Keep tests independent and repeatable.
  4. Seed only the data needed for each test.
  5. Test successful and failure scenarios.
  6. Verify HTTP status codes and response bodies.
  7. Test authentication and authorization.
  8. Avoid depending on production data.
  9. Run integration tests in CI/CD pipelines.
  10. Use realistic database behavior when testing database-specific features.

Load Testing Best Practices

  1. Define expected traffic before starting the test.
  2. Establish acceptable response-time and error-rate targets.
  3. Start with a baseline test.
  4. Increase traffic gradually.
  5. Monitor application, database and infrastructure metrics together.
  6. Test realistic user journeys, not just one endpoint.
  7. Use representative data.
  8. Run tests in an environment similar to production.
  9. Avoid running uncontrolled load tests against production.
  10. Repeat tests after significant performance changes.

14. Integration Testing vs Load Testing

AreaIntegration TestingLoad Testing
Main objectiveVerify components work together.Measure performance under traffic.
FocusFunctional correctness.Performance and reliability.
UsersUsually a small number of test clients.Many simulated virtual users.
Main checksResponse, business logic, database behavior.Response time, throughput, errors, resource usage.
ToolsxUnit, WebApplicationFactory, TestServer.k6, JMeter, NBomber, Azure Load Testing.
Typical executionCI/CD pipeline.Performance testing environment or scheduled pipeline.
ExampleVerify product creation works.Verify product creation performs well under expected traffic.

15. Where Do These Tests Fit in CI/CD?

A typical ASP.NET Core delivery pipeline can look like this:

Developer Commits Code Build Application Unit Tests Integration Tests Security Checks Deployment Load Testing Performance Analysis Production

In practice, short performance smoke tests can run in CI/CD, while larger load and stress tests are often scheduled or executed before major releases in a dedicated environment.

16. Common Interview Questions and Answers

Q1. What is integration testing in ASP.NET Core?

Integration testing verifies whether different application components, such as controllers, services, middleware and databases, work correctly together.

Q2. What is WebApplicationFactory?

WebApplicationFactory<TEntryPoint> is a testing utility provided by Microsoft.AspNetCore.Mvc.Testing. It creates a test host for an ASP.NET Core application and allows tests to send HTTP requests through an HttpClient.

Q3. What is the difference between unit testing and integration testing?

Unit testing checks individual components in isolation, whereas integration testing checks interactions between multiple components.

Q4. What is load testing?

Load testing measures application performance under an expected workload, including response time, throughput, error rate and resource consumption.

Q5. What is the difference between load testing and stress testing?

Load testing checks performance under expected traffic. Stress testing increases traffic beyond expected capacity to understand system limits and failure behavior.

Q6. What is throughput?

Throughput is the number of requests an application processes within a specified time, commonly measured in requests per second.

Q7. What is the p95 response time?

The p95 response time is the value within which 95% of requests complete. It helps identify slow requests that averages may hide.

Q8. Why should we use a separate database for integration testing?

A separate database protects production data, allows tests to run independently and makes test results repeatable.

Q9. Can integration tests use an in-memory database?

Yes. EF Core InMemory can be useful for simple tests, but it does not behave like a relational database. SQLite in-memory or a disposable real database is often more appropriate when relational behavior matters.

Q10. How do you identify performance bottlenecks?

Monitor response times, throughput, error rates, CPU, memory, database queries, connection pools and distributed traces. Use these measurements to identify the slowest part of the request flow.

Q11. What is spike testing?

Spike testing checks how an application handles a sudden increase or decrease in traffic.

Q12. Should load testing be performed directly in production?

Generally, use a production-like environment. Production testing should only be performed with explicit approval, controlled traffic, monitoring and a rollback plan.

17. Final Takeaway

  • Unit testing: Verifies individual components.
  • Integration testing: Verifies that application components work together.
  • Load testing: Verifies application performance under expected traffic.
  • Stress testing: Finds system limits under excessive traffic.
  • Endurance testing: Checks stability over an extended period.

For an ASP.NET Core application, a practical testing strategy is to use xUnit + WebApplicationFactory + SQLite/Testcontainers for integration testing and k6 or NBomber for load testing.

Official Documentation

🔙
Mocking with Moq in C# :👈 👉:Test-Driven Development (TDD)