Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Debugging xUnit tests in .NET Core and Visual Studio Code

I'm on a Mac, running .NET Core 1.0 and Visual Studio Code.

I have a console project and a test project. I have setup launch.json so that I can debug the console project.

How do I set up a launch configuration that launches my unit tests and attaches the debugger?

like image 222
driis Avatar asked Jul 01 '16 12:07

driis


People also ask

Does xUnit work with .NET core?

Sometimes, you want to write tests and ensure they run against several target application platforms. The xUnit.net test runner that we've been using supports . NET Core 1.0 or later, . NET 5.0 or later, and .

How do you write xUnit test cases in .NET core?

To write a test you simply create a public method that returns nothing and then decorate it with the Fact attribute. Inside that method you can put whatever code you want but, typically, you'll create some object, do something with it and then check to see if you got the right result using a method on the Assert class.


2 Answers

If you install the latest software and library, it is super easy to debug:

enter image description here

As you can see from the screenshot, just click "debug test" and debug it!

like image 190
Tyler Liu Avatar answered Sep 18 '22 22:09

Tyler Liu


See Tyler Long's answer. The steps below are not required in the newest versions of Visual Studio Code :)


I made a repository to demonstrate.

First off, the only way I could get the debugger to hit the test was to add a file, Program.cs, take control of the entry point from xUnit, and manually add code to test. It's not ideal, but I imagine you aren't going to be doing this very often, and it's easy to flip it back to normal.

Program.cs:

using System; namespace XUnitDebugging {     public class Program     {         public static void Main(string[] args)         {             var test = new TestClass();             test.PassingTest();             Console.WriteLine("Enter text...");             Console.ReadLine();          }     } } 

Next, in project.json add the following:

  "buildOptions": {     "emitEntryPoint": true,     "debugType": "portable"   }, 

project.json:

{   "version": "1.0.0-*",   "testRunner": "xunit",   "buildOptions": {     "emitEntryPoint": true,     "debugType": "portable"   },   "dependencies": {     "Microsoft.NETCore.App": {       "type": "platform",       "version": "1.0.0"     },     "xunit": "2.2.0-beta2-build3300",     "dotnet-test-xunit": "2.2.0-preview2-build1029"   },   "frameworks": {     "netcoreapp1.0": {       "dependencies": {         "Microsoft.NETCore.App": {           "type": "platform",           "version": "1.0.0"         }       }     }   } } 

This will allow you to debug an xUnit unit test project.

like image 35
Nick Acosta Avatar answered Sep 21 '22 22:09

Nick Acosta