Can't get XUnit tests working with Visual Stud

2020-07-11 07:30发布

问题:

For the life of me I can't get unit testing working in Visual Studio 2017 from the new msbuild-based netcoreapp1.0 xunit project template.

The requirement is for unit tests to work both inside Visual Studio (for the devs) and from dotnet test on the CLI for the automated build process however, I can't get either working consistently.

Here is what I have tried:

In an existing solution, create a new project and select .NET Core > xUnit Test Project.

Build project from Visual Studio, default test appears and runs successfully, now run dotnet test from powershell prompt, get:

 > dotnet test
 Test run for D:\...\bin\Debug\netcoreapp1.0\MyProj.dll(.NETCoreApp,Version=v1.0)
 dotnet exec needs a managed .dll or .exe extension. The application specified was 'C:\Program'

Or dotnet test with csproj file:

 > dotnet test MyProject.csproj
 (same error as above)

 > dotnet test ..\MySolution.sln
 Couldn't find a project to run test from. Ensure a project exists in D:\...
 Or pass the path to the project

If I add the xunit.runner.console or xunit.runner.msbuild nuget packages, it stops the unit tests working from inside Visual Studio.

How do I get both working at the same time?

Thanks!

回答1:

The bug you're hitting is present in Preview 3 and fixed in Preview 4. They didn't escape the command line when executing it, and since dotnet.exe is installed into C:\Program Files\dotnet by default, it always fails.

If you want to continue to use Preview 3, the simplest work-around is to edit your system PATH environment variable, and replace C:\Program Files\dotnet with C:\Progra~1\dotnet.



回答2:

I know this isn't a very good answer, but dotnet-test-xunit only support project.json files. VS 2017 forces you to switch to csproj files.

I found this on xunit twitter feed: If you're trying use @xunit in VS2017 RC w/ .NET Core, remove dotnet-test-xunit and use xunit.runner.visualstudio 2.2 beta 4 instead.



回答3:

With the latest RC.3 I was having issues with the tests not being discovered, and found out that when you run the built-in Test Explorer it says in the output that Microsoft.DotNet.InternalAbstractions 1.0.0 is missing. This was also issue in the previous versions of .NET Core, and the solution is the same, install the package from Nuget.