When working with unit tests in an ASP.NET Core application, you may want to run a specific test or a group of tests rather than executing all tests in your test project. The .NET Command Line Interface (CLI) provides options to filter and run specific tests based on their names or categories. This guide will walk you through the steps to run specific tests using the CLI.
Using the dotnet test
Command
The dotnet test
command is used to run tests in a specified test project. You can use various options to filter which tests to run.
How to Run a Specific Test
To run a specific test, you can use the --filter
option with the dotnet test
command. The filter can be based on the test name or other properties.
Step 1: Open Your Command Line Interface
Open your terminal (macOS/Linux) or command prompt (Windows).
Step 2: Navigate to Your Test Project Directory
Use the cd
command to navigate to the directory of your test project. For example:
cd /path/to/your/Utilities.Tests
Step 3: Run a Specific Test
Use the following command to run a specific test by its name:
dotnet test --filter "FullyQualifiedName~MyTestName"
In this command, replace MyTestName
with the name of the test you want to run. The FullyQualifiedName
property includes the namespace and class name along with the test name.
Example
Suppose you have a test named Utilities.Tests.MathTests.AdditionTest
that you want to run. You would execute the following command:
dotnet test --filter "FullyQualifiedName~Utilities.Tests.MathTests.AdditionTest"
After executing this command, you should see output indicating that only the specified test has been executed.
Running a Group of Tests
You can also run a group of tests by using the --filter
option with different criteria. For example, you can filter tests by category or by a common substring in their names.
Filtering by Category
If you have categorized your tests using attributes, you can run all tests in a specific category. For example:
dotnet test --filter "Category=Unit"
This command runs all tests that have the category Unit
.
Filtering by Name Substring
You can also run tests that contain a specific substring in their names:
dotnet test --filter "Name~Addition"
This command runs all tests that have "Addition" in their names.
Conclusion
Running specific tests or groups of tests using the CLI is a powerful feature that allows you to focus on particular areas of your code during development and debugging. By following the steps outlined in this guide, you can easily filter and execute the tests that are most relevant to your current work. Understanding how to effectively use the dotnet test
command with filters is essential for any .NET developer looking to implement efficient testing practices.