Assert exception from NUnit to MS TEST

瘦欲@ 提交于 2019-11-30 16:41:21

问题


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.


回答1:


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);



回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/8213569/assert-exception-from-nunit-to-ms-test

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!