Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create custom MSTest Assert-methods with "proper" callstack

I'm writing extension methods for testing values for my unit-test. A naïve example would be:

public static void ShouldBeTrue(this bool value)
{
    if(!value)
    {
        throw new AssertFailedException("Expected true");
    }
}

And using it in a test:

someBool.ShouldBeTrue();

Everything works, except that the line throwing the exception will be the one I end up on when double-clicking the failed test in the Test Results window, and in Test Result Details the throw-line is shown in the Error Stack Trace.

Is there a way round this, so that "someBool.ShouldBeTrue();":

  1. is the line that double-clicking the failing test in Test Results window opens?
  2. is the only line in stack trace?
like image 486
hcanber Avatar asked Nov 18 '10 13:11

hcanber


2 Answers

There's a class library already written for that: http://geekswithblogs.net/sdorman/archive/2009/01/31/adding-custom-assertions-to-mstest.aspx

There's a quote from the link above:

... For reference, those unavailable Asserts are:

  • Assert.IsNaN
  • Assert.IsEmpty
  • Assert.IsNotEmpty
  • Assert.Greater
  • Assert.GreaterOrEqual
  • Assert.Less
  • Assert.LessOrEqual
  • Assert.IsAssignableFrom
  • Assert.IsNotAssignableFrom
  • CollectionAssert.IsEmpty
  • CollectionAssert.IsNotEmpty
  • StringAssert.AreEqualIgnoringCase
  • StringAssert.IsMatch
  • FileAssert.AreEqual
  • FileAssert.AreNotEqual

...I have created a class library that includes all of them except the FileAssert methods and StringAssert.IsMatch. ... You can download the class from my SkyDrive public folder: https://skydrive.live.com/?cid=93d618d639ec9651&id=93D618D639EC9651%211283

like image 117
Nikita R. Avatar answered Nov 15 '22 05:11

Nikita R.


I think I found the answer. All you need to do is put your custom assertion classes/methods into a seperate assembly. You can have this as a seperate project in the same solution, if you like.

like image 31
Rob Cannon Avatar answered Nov 15 '22 05:11

Rob Cannon