Search code examples
c#mstestvs-unit-testing-framework

MSTest: CS0117 'Assert' does not contain a definition for 'ThrowsException'


I'm writing some unit tests with MSTest, using C#, MSVS 2015 and .Net 4.6.1.

This line:

Assert.ThrowsException<ArgumentOutOfRangeException>( () => 
  select.AllSelectedOptions[0]
);

Fails with this compile error:

CS0117 'Assert' does not contain a definition for 'ThrowsException'

My namespace is Microsoft.VisualStudio.TestTools.UnitTesting (the default when you create a unit test project in MSVS).

According to the documentation, Assert.ThrowsException(Action) should exist. But I don't see it in Intellisense ... and I'm getting the compile error.

I've tried a couple of different versions of MSVS (MSVS 2015 and MSVS 2019) and a couple of different versions of MSTest.

Q: Any ideas what might be wrong?


As Clint said below, I need to install MSTest v2 from NuGet in order to use Assert.ThrowsException<T>() in MSVS 2015.

But after doing this, MSVS isn't finding any of my tests anymore:

MSVS > Test > Run All (or "Test > Debug > All Tests"):

------ Discover test started ------
========== Discover test finished: 0 found (0:00:01.127375) ==========

Any suggestions?


Solution

  • You need to use [MSTest V2] to be able to Assert.ThrowsException

    Starting with VS2017, the in-box Unit Test Project templates use only MSTest V2.

    Now that you're on VS2015 you can install this package MSTest.Test from Nuget but make sure to remove the old test references like Microsoft.VisualStudio.QualityTools.UnitTestFramework before upgrading to this package

    Add > New Test project > Select MSTest project type

    After this you should be able to use Assert.ThrowsException<ArgumentOutOfRangeException>(

    To discover and execute tests also ensure to install MSTest.TestAdapter.

    Further Reading