【问题标题】:Assert exception from NUnit to MS TEST断言从 NUnit 到 MS TEST 的异常
【发布时间】:2011-11-21 14:41:26
【问题描述】:

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

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

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

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

【问题讨论】:

    标签: nunit mstest


    【解决方案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;
      }
    }
    

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

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

    【讨论】:

    • 在您的第二个代码块中检查异常!= null 不是更正确吗?
    • 您可以为其余的异常添加另一个 catch 块并说,“预期异常是 abc 但得到 xyz”。
    【解决方案2】:

    无耻插件,但我编写了一个简单的程序集,它使用 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)));
        }
    }
    

    更多信息here

    【讨论】:

    • 我没有什么可以给的,但我很感激你的!我希望你没有对我的评论感到生气。虽然我在 SO 方面的专长在于完全不同的主题领域,但我会尽量通过编辑来回馈网站,并鼓励像你这样的人发布更高质量的答案。所有这些加起来就是一个对其他人来说是更有价值的资源的网站。
    【解决方案3】:

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

    【讨论】:

      猜你喜欢
      • 2013-03-16
      • 2012-08-15
      • 2019-11-21
      • 2011-02-23
      • 1970-01-01
      • 1970-01-01
      • 2011-01-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多