How to Add Assert.Throws() to MSTest
One of the frustrations with MSTest is that it is falling behind the times for unit testing when compared to other testing frameworks.
I find it a real shame this this is happening and that MSTest didn’t gain an Assert.Throws method at any point along the way and that we still have to stick the ExpectedException attribute on our test methods, not to mention the fact that the expected message in the attribute still doesn’t get checked properly.
Now you may be asking “What’s wrong with just using the attribute on the test method?” Simple – consider what happens if the exception your looking for gets thrown by a line other than the one you were expecting it to be thrown on? You will get a false positive. A test that passes even though it should be breaking. Nasty stuff that.
I think the Assert.Throws() method from xUnit is so much better because it’s very explicit. When you use it you know exactly what line the exception should be thrown on and you can also check that the message provided by the exception matches your expectations.
So, why not just use the xUnit asserts thent? Well, we can. We can actually keep the MSTest runner and use all the xUnit Asserts instead of the MSTest ones. Not only do we gain the Assert.Throws() method but we also get xUnits Assert.Equals() method, which can compare arrays and lists, and more.
Here’s how…
- Add a reference to xUnit to your test project
- Add “using Assert=Xunit.Assert;” to your code
- Use the Assert.Throws method as you would in an xUnit test.
Pretty tough, huh? Here’s an example of it in action:
using System;
using System;
using System.Collections.Generic;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Assert=Xunit.Assert;
namespace MyTests
{
[TestClass]
public class SomeSillyTests
{
[TestMethod]
public void ShouldThrowNullReferenceException()
{
string myNullString = null;
int length;
Assert.Throws(() => length = myNullString.Length);
}
[TestMethod]
public void ShouldCompareListEquality()
{
List<string> List1 = new List<string>() { "a", "b", "c" };
List<string> List2 = new List<string>() { "a", "b", "c" };
Assert.Equal(List1, List2);
}
}
}
Enjoy your new found Assert freedoms! :-) P.S. The same techniques can be applied to using the NUnit or MBUnit Asserts or your own Assertion library of choice.