Specflow 中的依赖注入,每个功能是否有一个上下文对象?

Dependency injection in Specflow, is it one context object per feature?

在 Specflow 中,可以使用 dependency injection

在步骤定义之间共享上下文

这是否意味着您最终会为每个功能得到不同的 "context" class?

如果是这样,这会不会导致跨功能共享步骤定义变得不切实际?您是否假设字段已设置?

Does this mean that you end up with a different "context" class for each feature?

我不认为会是这样。在编写规范时,您肯定会提到系统的几个 "kind" 部分。假设我们有以下场景:

Scenario: List todo items
  Given I'm registered as user@example.com
  And I'm logged in as user@example.com
  And I add a todo item with the text 'Listen to Whosebug podcast'
  When I list all my todo items
  Then I should see the following items
    | Text                            | Completed |
    | Listen to Whosebug podcast | false     |

在这种情况下,我们与系统的几个部分进行交互:

  • 注册
  • 身份验证
  • 待办事项创建
  • 待办事项列表

在实现此功能的步骤时,我们可能会得到这样组织的步骤文件:

  • AuthSteps
    • Given I'm registered as __
    • Given I'm logged in as __
  • TodoItemsSteps
    • I add a todo item with the text '__'
    • When I list all my todo items
    • Then I should see the following items

在这种使用上下文注入的情况下,我们希望共享 CurrentUser 的值,以便能够像 "When I list all my todo items" 那样引用当前用户。这样,任何其他 stepFile 中的任何其他步骤都可以与之前的步骤相关联。

另一方面,我不会将上下文注入与 When I list all my todo items 的结果一起使用,因为共享这些功能特定问题的唯一步骤将在同一个功能文件中。您可以有 then "statement" 的多种变体,例如 Then I should see n items.

尽管我确实认为您可能有多个 class 使用上下文注入来共享您正在构建的服务的依赖项,或者可能是服务本身(存储、会话等)。 .)

对象的生命周期是每个场景。这意味着,您为每个 Scenario/Test 获得一个单独的实例。

这样您就可以在不同的测试之间共享一个状态,因此它们不会相互影响。

恕我直言,您应该在系统中使用基于 'domains' 的上下文,而不是基于测试中的功能。

我们发现像这样的上下文提供了很好的关注点封装并且更合乎逻辑。因此,您可能有 UserContextCartContextPaymentContext 等,然后在这些上下文中需要函数或数据的步骤在构造函数中请求它们。

正如 Andreas 所说,specflow 将管理您的上下文,以便它们在每个场景中都是独立的。

不依赖于功能。每个场景都有自己的上下文,它会随着场景结束而结束,不同的功能可以使用相同的上下文