从NUnit向MS TEST断言异常

时间:2011-11-21 14:41:26

标签: nunit mstest

我有一些测试,我在异常中检查参数名称。 我如何在MS TEST中写这个?

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

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

我一直希望有更简洁的方式,所以我可以避免在测试中使用try catch块。

3 个答案:

答案 0 :(得分:29)

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

您可以使用上面的扩展方法作为测试帮助程序。以下是如何使用它的示例:

// test method
var exception = ExceptionAssert.Throws<ArgumentNullException>(
              () => organizations.GetOrganization());
Assert.AreEqual("lawbaseFixedContactRepository", exception.ParamName);

答案 1 :(得分:7)

无耻的插件,但我编写了一个简单的程序集,它使用nUnit / xUnit样式的 Assert.Throws()语法在MSTest中使断言异常和异常消息更容易和更易读。 / p>

您可以使用以下方式从Nuget下载该软件包: PM&gt;安装包MSTestExtensions

或者您可以在此处查看完整的源代码:https://github.com/bbraithwaite/MSTestExtensions

高级指令,下载程序集并继承自 BaseTest ,您可以使用 Assert.Throws()语法。

Throws实现的主要方法如下:

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

更多信息here

答案 2 :(得分:3)

由于MSTest [ExpectedException]属性不检查消息中的文本,因此最好的办法是尝试捕获并在异常Message / ParamName属性上设置Assert。