从NUnit向MS TEST断言异常

cpo*_*ign 14 nunit mstest

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

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

Assert.AreEqual("lawbaseFixedContactRepository", exception.ParamName);
Run Code Online (Sandbox Code Playgroud)

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

Dan*_*Dan 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;
  }
}
Run Code Online (Sandbox Code Playgroud)

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

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


Bra*_*ite 7

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

您可以使用以下命令从Nuget下载程序包:PM> Install-Package 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)));
    }
}
Run Code Online (Sandbox Code Playgroud)

更多信息在这里.