1

新的 NUnit 版本 3.x 不再支持ExpectedExceptionAttribute。有一个Assert.Throws<MyException>()代替。可能是一个更好的逻辑概念。但我没有找到任何旧货的替代品MatchType——有吗?MyException可以用许多参数抛出,在 NUnit 2.x 中,我可以比较包含某个文本片段的异常消息,以了解使用了哪个参数(当然,我不会有几十个异常类合乎逻辑的)。NUnit 3.x 如何处理这个问题?我找不到提示。

使用 NUnit 2.x,我将执行以下操作:

[Test]
[ExpectedException(ExpectedException=typeof(MyException),  ExpectedMessage="NON_EXISTENT_KEY", MatchType=MessageMatch.Contains)]
public void DeletePatient_PatientExists_Succeeds()
 {
    Person p    = new Person("P12345", "Testmann^Theo", new DateTime(1960, 11, 5), Gender.Male);
    MyDatabase.Insert(p);

    MyDatabase.Delete(p.Key);

    // Attemp to select from a database with a non-existent key.
    // MyDatabase throws an exception of type MyException with "NON_EXISTENT_KEY" within the message string,
    // so that I can distinguish it from cases where MyException is thrown with different message strings.
    Person p1   = MyDatabase.Select(p.Key);
 }

如何使用 NUnt 3.x 做类似的事情?

请考虑我的意思:NUnit 提供的方法不足以识别引发异常的参数,所以这是一个不同的问题。

4

2 回答 2

1
var ex = Assert.Throws<MyException>(()=> MyDatabase.Select(p.Key));
StringAssert.Contains("NON_EXISTENT_KEY", ex.Message);
于 2017-02-06T13:25:56.280 回答
-1

看起来,确实存在提供此功能的可能性(甚至比上述更清晰),尽管不是在 NUnit 3 本身中,而是在FluentAssertions( http://www.fluentassertions.com/ ) 中。在那里,你可以做类似的事情

 Action act = () => MyDatabase.Select(p.Key);
 act.ShouldThrow<MyException>().Where(ex => ex.Message.Contains("NON_EXISTENT_KEY"));

出于我所有的实际目的,这解决了这个问题。

于 2017-02-06T13:10:51.717 回答