跨测试共享 AutoFixture

Sharing AutoFixture across tests

跨多个测试方法共享 Fixture 的实例是一种好的做法吗?

还是为每个测试方法创建一个 Fixture 的新实例更好?

最佳做法是什么?如果你能提供一个反模式的源码给我就好了。

AutoFixture 的名称来自 Fixture 模式:

"a test fixture is all the things we need to have in place in order to run a test and expect a particular outcome. [...] Setting up the test fixture is the first phase of the Four-Phase Test."

虽然 Shared Fixture 是一种概念上的可能性,但它有很多缺点,因为它使测试彼此独立变得更加困难。

AutoFixture 明确设计用于提供可重复使用的库来创建 Fixture,而不必为您需要创建的每种新类型的测试上下文手动编码Fixture Objects

有人创建单个 (AutoFixture) Fixture 对象并在多个测试方法中共享它,但我一直不明白他们为什么这样做;它几乎违背了 AutoFixture 的目的。

不过,如果您觉得这样的设置有用,我凭什么告诉您停止这样做呢?无论你的船如何漂浮......然而,AutoFixture 的设计考虑了每个测试方法一个 Fixture 实例的明确用例,我没有看到以其他方式进行的任何优势。

最佳做法是利用AutoFixture.Xunit or AutoFixture.NUnit2并避免在测试方法或函数内部或外部创建Fixture实例。

如果您不能使用上述任何 Glue 库,则在使用 new 实例时被认为是 good 实践每个测试中的 Fixture class。

使用 Fixture class 的新实例允许您控制 AutoFixture 在每个特定测试中的行为方式,因为您可以对其应用自定义,并且它们不会影响所有其他测试。