Search code examples
visual-studiounit-testingmstest

Detect how a unit test was triggered


We have an environment that has a very long running unit test. The method for this unit test is called "RunDataTest" which is populated using DynamicData. The DynamicData comes from a method GetUnitTestConfig that reads the configuration for each individual unit test from a network drive.

On the server/build agent I want to run all unit tests.

But on my local machine I want to see a list of these unit tests in my Test Explorer, but I don't want to start them when I press "Run All Unit Tests": I want to start them individually when explicitly clicking on the unit test and start only the selected unit test. This means I want to detect who/how the unit tests was triggered or better which Visual Studio function triggered the unit test.

My problem is that I'm lacking an indicator to find out how the unit test was triggered. Is there any property to find this out?


Solution

  • While you are asking how to detect when a unit test is triggered, the real problem is that these long-running tests are being triggered locally where you would like to run only fast tests. There are a couple of solutions to this problem that mostly boil down to filtering tests in Visual Studio Test Explorer.

    1. Put all of your fast-running tests in a single folder. Filter by full name in Visual Studio Test Explorer: fullname:ProjectNamespace.Folder

    2. Categorize tests using the [TestCategory(string)] attribute as either fast or slow:

      [TestMethod]
      [TestCategory("fast")]
      public void ReallyFastUnitTest() { ... }
      
      [TestMethod]
      [TestCategory("slow")]
      public void TestThatLoadsDataFromNetworkDrive() { ... }
      

      Then filter by category in Visual Studio Test Explorer: trait:fast

    More info about filtering tests in Test Explorer: https://learn.microsoft.com/en-us/visualstudio/test/run-unit-tests-with-test-explorer?view=vs-2022#group-and-filter-the-test-list