A login test should sometimes expect rejection. If a wrong password causes the action to throw immediately, the scenario stops before its next step can check the error message. The Attempt Action pattern separates performing an action from verifying its expected outcome. section 15.5
Keep ordinary execution strict, and opt in only when the scenario needs to inspect the outcome:
- Run normal actions in a mode that throws when they fail. This helps expose unexpected failures promptly. section 15.5
- For an attempted action, capture a result recording whether it ran, whether it succeeded, and either its return value or its failure. section 15.5
- In the subsequent verification step, assert the outcome the scenario expects. A recorded failure is not a passing test until that assertion checks it. section 15.5
Rejecting a wrong password
“When the customer attempts to log in with a wrong password” initiates the login and saves its result. “Then the login should fail with ‘Invalid credentials’” checks that the attempt ran, failed, and produced the expected message. The steps can say what the business expects without putting exception handling into every login scenario. section 15.5
Listing 15.18 Use AttemptExecute in step definitions
*** StepDefinitions/AuthenticationStepDefinitions.cs ***
public class AuthenticationStepDefinitions(
AuthenticationApiDriver authApiDriver)
{
private TestActionResult<LoginResponse> loginResult =
TestActionResult<LoginResponse>.NotExecuted;
[When("the customer attempts to log in with a wrong password")]
public async Task WhenTheCustomerAttemptsToLogInWithAWrongPassword()
{
loginResult = await authApiDriver
.Login(DomainDefaults.CustomerName, DomainDefaults.WrongPassword)
.AttemptExecute();
}
[Then("the login should fail with {string}")]
public void ThenTheLoginShouldFailWith(string expectedMessage)
{
Assert.IsTrue(loginResult.WasExecuted);
Assert.IsFalse(loginResult.Success);
StringAssert.Contains(loginResult.Error!.Message, expectedMessage);
}
...
}The step definitions show the handoff: AttemptExecute stores the login result in the When step; the Then step verifies failure and its message. section 15.5
The pattern supports reusable step definitions when one action may have several valid outcomes. It keeps the decision about what should happen in the verification step, while preserving a strict default for actions whose failure is unexpected. section 15.5 section 15.9
