将NUnit的异常声明为MS TEST [英] Assert exception from NUnit to MS TEST

查看:69
本文介绍了将NUnit的异常声明为MS TEST的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些测试,其中我正在检查异常的参数名称. 我该如何在MS TEST中编写代码?

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

我一直希望使用更整洁的方式,这样我就可以避免在测试中使用try catch块.

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

推荐答案

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

这篇关于将NUnit的异常声明为MS TEST的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆