Search code examples
c#unit-testing.net-coremsbuild

How to create a custom task only for unit testing?


Currently, unit tests in c# needs a lot of shell parameters: How to simplify the unit tests execution in c# when shell is used instead Visual Studio?

That's why I'm trying to create a custom task to be able to run the tests and code coverage with one line and also keep it cross-platform for windows developers.

I tried something like dotnet foo but I could not find any official or workaround.

dotnet + msbuild

The following task works

<Target Name="Foo">
  <Message Text="This is a Foo task" />
</Target>

dotnet msbuild -target:Foo

But the problem is: This command loads the main ./src/Main.csproj, not the ./test/Test.csproj of tests, so the custom task (for unit test) should be in the Main.csproj, which doesn't make sense

./src
./src/Controllers
./src/Controllers/**
./src/Main.csproj
./src/Startup.cs
./test
./test/Controllers
./test/Controllers/**
./test/Test.csproj

I tried to pass the relative location of ./test/Test.csproj with

  • --project without success

But another error is raised: error MSB1001: Unknown switch.

So my question is:

How to create a custom task only for unit testing?


Solution

  • There is no --project switch for MSBuild. See MSBuild command-line reference. Also see dotnet command reference.

    You can run the Foo target of your test project with the following command:

    dotnet msbuild -target:Foo ./test/Test.csproj
    

    You can run all your test projects with the following command in the folder that contains the solution file:

    dotnet test