When performing Acceptance tests, you sometimes need to pass data between the individual steps within a scenario. In other words, data needs to be exchanged between different bindings during the execution of the test.
SpecFlow provides several ways of sharing data between bindings.
Let’s talk about third option in more detail. With this simple dependency injection you can group the shared state to context-classes, and inject them into every binding class that is interested in that shared state.
To use context injection, you need to do the following.
public class UserLoginDetails { public string Email { get; set; } public string UserName { get; set; } public string Password { get; set; } public string Domain { get; set; } }
public class LoginSetupSteps { private readonly UserLoginDetails _userLoginDetails; public LoginSetupSteps (UserLoginDetails userLogin) { _userLoginDetails = userLogin; } [Given(@"User has Logged in with UserName '(.*)'")] public void GivenUserHasLoggedInWithUserName (string userName) { _userLoginDetails.UserName = userName; } }
public class LoginVerificationStpes { private readonly UserLoginDetails _userLoginDetailsToBeVerified; public LoginVerificationStpes(UserLoginDetails loginDetails) { _userLoginDetailsToBeVerified = loginDetails; } [Then(@";user should be allowed to use MyWorkNow")] public void ThenUserShouldBeAllowedToUseMyWorkNow() { AssertThatUserIsAllowedToUseMyWorkNow(_userLoginDetailsToBeVerified); } }
The following caveats should be kept in mind when using context injection.