断言从NUnit异常到MS测试

问题描述:

我有一些测试,我在检查参数名称在例外。 我如何在MS TEST中编写此代码?断言从NUnit异常到MS测试

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

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

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

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

像你在你的第二个代码块中围绕这个 – cpoDesign

+0

工作的方式不是更正确的检查异常!= null? – syclee

+0

您可以为其余的异常添加另一个catch块,并说“预期的异常是abc但得到了xyz”。 – Hash

由于MSTest [ExpectedException]属性不检查邮件中的文本,所以最好的办法就是尝试...在异常消息/参数名属性上捕获并设置Assert。

无耻的插头,但我写了一个简单的装配,使得使用Assert.Throws()语法断言异常和异常信息更容易一点,在MSTest的可读性更强采用nUnit/xUnit的风格。

您可以通过下载从的NuGet包:PM>安装,包装MSTestExtensions

或者,你可以看到完整的源代码在这里:https://github.com/bbraithwaite/MSTestExtensions

高级指令,下载安装和继承BaseTest并且您可以使用Assert.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

+0

@joran我应该补充,我等待着你对这个问题的答案... –

+0

我没有什么可以奉献的,但我很感激你的!我希望你对我的评论没有冒犯。虽然我在专业领域的专业知识在于完全不同的学科领域,但我尽可能地通过编辑回馈网站,并鼓励像您这样的人提出更高质量的答案。这一切都归功于一个对其他人来说更有价值的资源。 – joran

+0

@joran公平够:) –