强制.NET测试方法从内部失败

oli*_*i.G 2 .net c# unit-testing

我的大多数测试方法首先尝试两个或三个简单的操作,这应该引发异常,然后开始真正的工作.在Java中,我会这样写:

@Test
public void TestSomething() {

    try {
        testedClass.testedMethod(null);
        fail();
    catch (IllegalArgumentException ex) {
        // OK
    }

    // and now let's get to the point ...
    // ...

} 
Run Code Online (Sandbox Code Playgroud)

我想在C#中坚持这种习惯,但似乎没有办法强迫测试方法失败.我已经看了一会儿,但没有运气.我错过了什么吗?

PS:我知道测试这些情况的正确方法是:

[TestMethod]
[ExpectedException(ArgumentNullException)]
public void TestSomethingWithNull() {

    testedClass.TestedMethod(null);

}

[TestMethod]
public void TestSomething() {

   // now the non-trivial stuff...

}
Run Code Online (Sandbox Code Playgroud)

......但是,我不喜欢这个.当我有,比方说,我的测试类中的6个测试方法,并且每个测试应该从覆盖三个琐碎的,一行情况开始,这应该引发异常,使用这种方法将我的6个测试变成18个.应用程序,这确实污染了我的测试资源管理器,并使结果更难以扫描.

并且假设我想测试一个方法,该方法的职责是验证某个类的给定实例的每个属性,如果任何值不正确则引发ValidationException.这可以通过一个TestValidation()测试轻松处理,但是使用这种方法,将其转换为:

  • TestValidationWithNull();
  • TestValidationWithInvalidProperty1();
  • TestValidationWithInvalidProperty2();
  • TestValidationWithNullProperty2();

想象一下,你有20个属性...... :)

当然,如果这是唯一的方法,我会咬人.

Ser*_*kiy 12

您可以使用Assert.Fail()或抛出NotImplementedException(如果您正在测试的方法尚未实现).

但是为了测试代码是否抛出异常,我建议你使用ExpectedException属性(如果你坚持使用MSTest) - 如果不抛出异常,测试将失败.