如何使 NUnit 中的 TestFixtureSetup 失败

How to fail a TestFixtureSetup in NUnit

我目前正在 NUnit 中编写一些集成测试,这些测试需要在 [TestFixtureSetUp] 方法内部完成一些设置。如果在设置过程中出现问题(例如无法连接到服务器),使方法失败并将其传达给 NUnit 的正确方法是什么?我会抛出异常,还是有特定的 NUnit 方法可以调用?

  • 如果您调用的方法在失败时抛出异常,那么只要让它们这样做,NUnit 运行程序就会捕获它们并使 fixture 单元测试失败。

  • 如果您有一个应该触发失败的条件,请使用 Assert()(就像所有其他测试一样)

  • 否则,您可以显式调用 NUnit 实用程序方法 Assert.Fail(message).

    大多数 Assert 方法允许您定义对您有帮助的消息 快速诊断原因。

您可能还会发现这个 ShoudBe NUnit wrapper library useful that will simplify and type check your assertions (replacing them with <expr>.ShouldBeXXX() fluent extension methods) and removing the need to write failure messages (it reports the expression that failed by reading your source code) + really useful enumeration messages. Because it's just a layer on top of NUnit, you can use it with your existing NUnit tools like Reshaper, NUnit Runner and CI. You can also safely add new ShouldBe unit tests to an old NUnit test suite or combine it with NUnit features like parameterised unit tests