0

In C#, I have a method which throws an exception when a certain condition is true. I am supposed to write a unit test method to verify that.

Since the method being tested doesn't return a boolean value, I can't use Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsTrue method. Which assert method can I use? Thanks.

Tim
  • 1
  • 141
  • 372
  • 590
  • @sasha_gud Yes, but those answers are horribly out of date – Justin Jun 01 '17 at 20:40
  • If you're open to using an assertion library, see https://stackoverflow.com/questions/40543708/testing-exception-messages-with-shouldly – TrueWill Jun 01 '17 at 20:42

1 Answers1

0

Use Assert.Throws, like so:

var ex = Assert.Throws<ArgumentNullException>(() => My.Method(null));
Assert.Equals("foo", ex.ParamName);

This works in XUnit and in the later versions of MSTest (install MSTest as a NuGet package to get up-to-date versions)

Justin
  • 84,773
  • 49
  • 224
  • 367
  • Thanks. Are MSTest and `Microsoft.VisualStudio.TestTools` separate from each other? – Tim Jun 01 '17 at 21:27
  • @Tim MSTest used to be (still is) shipped with Visual Studio - the `Microsoft.VisualStudio.TestTools` assemblies that come with Visual Studio is the older version of MSTest (that doesn't include the `Assert.Throws` methods). Newer versions of Visual Studio reference the NuGet package when you create a test project, rather than those assemblies. – Justin Jun 01 '17 at 21:41