Course contentsShow
← C#
Lesson 1618 of 1,90815. Software Quality and TestingFree lesson

Data-Driven Testing with Inline Data

Optimize test coverage by running identical test logic against multiple input sets.

In this lesson, you will learn how to maximize your test coverage by executing the same test logic against multiple input variations using [InlineData].

The Problem: Repetitive Test Logic

When writing unit tests, you often encounter scenarios where the logic being tested remains constant, but the input data changes. For example, testing a TaxCalculator service requires verifying that various income levels result in the correct tax bracket. Without data-driven testing, you might find yourself writing five nearly identical test methods, leading to "code bloat" and making your test suite harder to maintain.

The Solution: [InlineData]

By using the [Theory] attribute instead of [Fact] in xUnit, you instruct the framework that the test method will be executed multiple times with different parameters. The [InlineData] attribute allows you to inject these parameters directly into your method arguments.

This approach enforces the AAA (Arrange-Act-Assert) pattern while keeping your test suite DRY (Don't Repeat Yourself). If the underlying business logic changes, you only update the test logic once rather than in five different places.

Concrete Example

Here is how you can use [InlineData] to validate a simple discount service:

[Theory]
[InlineData(100, 0.10, 90)]   // 10% off 100 is 90
[InlineData(200, 0.20, 160)]  // 20% off 200 is 160
[InlineData(50, 0.0, 50)]     // 0% off 50 is 50
public void CalculateDiscount_ShouldReturnExpectedResult(decimal amount, decimal discount, decimal expected)
{
    // Arrange
    var service = new DiscountCalculator();

    // Act
    var result = service.ApplyDiscount(amount, discount);

    // Assert
    Assert.Equal(expected, result);
}

In this example, xUnit executes the test method three times. If one case fails, the test runner identifies exactly which data set caused the failure, maintaining excellent visibility into your system's edge cases without sacrificing code quality.

Key Takeaway: Use [Theory] combined with [InlineData] to decouple your test logic from your input data, allowing you to scale your test coverage efficiently without duplicating your AAA structure.