如果 [AssemblyInitialize] 已存在于具有 Specflow 的测试项目中,则会出错

Error if the [AssemblyInitialize] already exists in the test project with Specflow

我已将 Specflow 从 3.0.225 更新到 3.1.62,但收到错误 Tests_Integration_MSTestAssemblyHooks: Cannot define more than one method with the AssemblyInitialize attribute inside an assembly.

原因显然是我的项目中已经有了 [AssemblyInitialize] 属性。我该如何解决?

原因是 Specflow 在后台生成了另一个文件,其中定义了 AssemblyInitialize/AssemblyCleanup 挂钩。为了解决这个问题,应该使用 Specflow 提供的钩子,即 BeforeTestRun/AfterTestRun。像这样:

[Binding] // add the Binding attribute on the class with the assembly level hooks
public abstract class SeleniumTest 
{
  // it used to be [AssemblyInitialize]
  [BeforeTestRun]
  public static void AssemblyInitialize(/* note there is no TestContext parameter anymore */)
  {
    // ...
  }

  // it used to be [AssemblyCleanup]
  [AfterTestRun]
  public static void AssemblyCleanup()
  {
    // ...
  }
}