Using Build and Test Tasks from the Parent Directory of src/test with VS Code

Full source code available here.

Many .NET repos follow the convention of src and test directories side by side and have no solution file. This works well with Visual Studio Code if you have two instances open, one for each subdirectory.

But if you want to have both directories open in a single instance of VS Code it is not as simple to perform tasks like building and testing.

.vscode in parent dir

The first step is to add a .vscode directory at the same level as src and test. Then add a tasks.json file, you can do this by hand or by getting VS Code to create a basic version of this file for you.

I am going to add three tasks to the file, one to build the src, one to build the test, and one to run the tests.

An empty tasks.json

If you want to, you can start with an empty tasks.json file in the .vscode directory and add the following -

{
    "version": "2.0.0",
    "tasks": [        
    ]
}

Building the src

Next, add the task to build the src project to the tasks array. Note in the args that the path includes src/. This task is named build-src.

{
    "label": "build-src",
    "command": "dotnet",
    "type": "process",
    "args": [
        "build",
        "${workspaceFolder}/src/MoqCountExecutionTimes.csproj",
    ],
    "group": "build",
    "problemMatcher": "$msCompile"
},

Building the test

Add the task to build the test project. Again, note how I am pointing to the test directory in the arguments. This task is named build-test.

{
    "label": "build-test",
    "command": "dotnet",
    "type": "process",
    "args": [
        "build",
        "${workspaceFolder}/test/MoqCountExecutionTimes.Tests.csproj",
    ],
    "group": "build",
    "problemMatcher": "$msCompile"
},

Running the tests

Finally, add a task to run the tests. Note the "isTestCommand": true, that is what tells VS Code that this is a test task.

{
    "label": "test",
    "command": "dotnet",
    "type": "process",
    "args": [
        "test",
        "${workspaceFolder}/test/MoqCountExecutionTimes.Tests.csproj"
    ],
    "isTestCommand": true
}

That’s about it. You should now be able to see three tasks in the command palette.

Full source code available here.

comments powered by Disqus

Related