Assert exception from NUnit to MS TEST

2019-02-12 01:11发布

I have some tests where i am checking for parameter name in exception. How do i write this in MS TEST?

ArgumentNullException exception = 
              Assert.Throws<ArgumentNullException>(
                            () => new NHibernateLawbaseCaseDataLoader( 
                                               null, 
                                               _mockExRepository,
                                               _mockBenRepository));

Assert.AreEqual("lawbaseFixedContactRepository", exception.ParamName);

I have been hoping for neater way so i can avoid using try catch block in the tests.

标签: nunit mstest
3条回答
Root(大扎)
2楼-- · 2019-02-12 01:25

Since the MSTest [ExpectedException] attribute doesn't check the text in the message, your best bet is to try...catch and set an Assert on the exception Message / ParamName property.

查看更多
Fickle 薄情
3楼-- · 2019-02-12 01:27
public static class ExceptionAssert
{
  public static T Throws<T>(Action action) where T : Exception
  {
    try
    {
      action();
    }
    catch (T ex)
    {
      return ex;
    }

    Assert.Fail("Expected exception of type {0}.", typeof(T));

    return null;
  }
}

You can use the extension method above as a test helper. Here is an example of how to use it:

// test method
var exception = ExceptionAssert.Throws<ArgumentNullException>(
              () => organizations.GetOrganization());
Assert.AreEqual("lawbaseFixedContactRepository", exception.ParamName);
查看更多
你好瞎i
4楼-- · 2019-02-12 01:33

Shameless plug, but I wrote a simple assembly that makes asserting exceptions and exception messages a little easier and more readable in MSTest using Assert.Throws() syntax in the style of nUnit/xUnit.

You can download the package from Nuget using: PM> Install-Package MSTestExtensions

Or you can see the full source code here: https://github.com/bbraithwaite/MSTestExtensions

High level instructions, download the assembly and inherit from BaseTest and you can use the Assert.Throws() syntax.

The main method for the Throws implementation looks as follows:

public static void Throws<T>(Action task, string expectedMessage, ExceptionMessageCompareOptions options) where T : Exception
{
    try
    {
        task();
    }
    catch (Exception ex)
    {
        AssertExceptionType<T>(ex);
        AssertExceptionMessage(ex, expectedMessage, options);
        return;
    }

    if (typeof(T).Equals(new Exception().GetType()))
    {
        Assert.Fail("Expected exception but no exception was thrown.");
    }
    else
    {
        Assert.Fail(string.Format("Expected exception of type {0} but no exception was thrown.", typeof(T)));
    }
}

More info here.

查看更多
登录 后发表回答