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

Category and Filter Attributes

Organize test execution groups to separate fast unit tests from slow integration checks.

In this lesson, you will learn how to use Category and Filter Attributes to partition your test suite, allowing you to decouple high-speed unit tests from resource-intensive integration checks.

As your test suite grows, running the entire battery of tests for every minor code change becomes a bottleneck. While unit tests should execute in milliseconds, integration tests often involve database connections, message broker setups, or external API calls. To maintain high developer velocity, we use filtering mechanisms—such as [Trait] in xUnit or [Category] in NUnit—to label and selectively execute tests.

Categorizing Your Tests

By tagging your test methods, you create metadata that test runners can process. For instance, you might label a fast calculation test as "Unit" and a test that verifies a database schema as "Integration".

public class OrderServiceTests
{
    [Fact]
    [Trait("Category", "Unit")]
    public void CalculateTax_ShouldBeFast() { /*...*/ }

    [Fact]
    [Trait("Category", "Integration")]
    public void SaveOrder_ShouldPersistToDatabase() { /*...*/ }
}

Filtering Execution

Once these categories are in place, your CI/CD pipeline or local CLI tools can isolate specific groups. Instead of running everything, you can target your development loop by executing only the "Unit" category:

dotnet test --filter "Category=Unit"

This approach is vital for the "Testable Architecture Mindset" we discussed earlier. It allows you to run "Unit" tests on every save, while reserving "Integration" tests for pre-commit hooks or nightly builds. This separation ensures that your feedback loop remains tight, preventing the "slow test" syndrome that often causes developers to skip running tests entirely.

By applying this filter-first strategy, you protect your infrastructure from unnecessary load and keep the development workflow efficient, even as your project scales to thousands of tests.

Key Takeaway: Use Category and Filter Attributes to classify tests by speed and dependency, enabling selective execution that keeps your development cycle fast without sacrificing comprehensive coverage.