Pedro Roque

Pedro Roque

Software Architect

Running tests in .NET Core projects using VS Code

April 21, 2021
testing
.NET

In recent months, I've been making an effort to migrate my entire workflow to VS Code, instead of Visual Studio.

VS Code is extremely fast, highly extensible, runs on any operating system, and is free!

One of the advantages of VS Code can also be its Achilles' heel: since it is not a normal IDE optimized for a specific workflow, everything is done through configuration. And operations that we don't even think about in Visual Studio require us to spend a few minutes configuring them to our liking here.

One such case is running tests. While in Visual Studio, we only need to create the project and maybe add a nugget, here we need to choose how we will run the tests and configure it accordingly.

The first method is to run the tests via the CLI. To do this, we need to configure a new task. VS Code has a specific folder for project configuration files:

configuration files

We need to add the test task to tasks.json:

1{
2    "version": "2.0.0",
3    "tasks": [
4        {
5            "label": "test solution",
6            "command": "dotnet",
7            "type": "process",
8            "args": [
9                "test",
10                "--no-restore",
11                "${workspaceFolder}/src/HighOnSoftware.sln"
12            ]
13        },
14    ]
15}

Label is the name assigned to the task, command is the .NET CLI (dotnet), and args are just the list of arguments you would normally use if you were using dotnet in the command line.

After creating the task, you can run it either through the command panel or by assigning a keybinding.

The second option is using the .NET Core Test Explorer extension.

After installing the extension, you might be surprised when you open the test panel.

unspecified test project path

In .vscode folder, we can configure the path of our test projects.:

1{
2    "dotnet-test-explorer.testProjectPath": "**/*Tests.csproj",
3    "dotnet-test-explorer.autoWatch": true,
4    "dotnet-test-explorer.autoExpandTree": true,
5    "dotnet-test-explorer.treeMode": "merged",
6    "dotnet-test-explorer.showCodeLens": true,
7    "dotnet-test-explorer.runInParallel": true
8}

After that, our tests are discovered and executed normally:

Execução de testes

The .vscode folder should be versioned so that the parameters used can be shared by the entire development team. For some reason, I've seen several situations where this folder is added to .gitignore, which doesn't make any sense to me!