This post is the second in the series of posts regarding implementing SpecFlow for unit tests within BDD. This section looks at how tests can be written to check that the correct exceptions are thrown under certain conditions. An understanding of Behaviour-driven development (BDD) with Specflow - Part 1 and Using the Mediatr pipeline with Fluent Validation is assumed.
Firstly, two steps must be written. A step to add the user without a name and a second to return the error message.
The exception is recalled from the text context and verified to ensure it matches the expected error message that is passed into the step. This step is highly reusable as can be used with any test that checks to see the return error message.
Now the steps are in place, the scenario can be written.
Finally, a simple rule is written in the AddUserValidator (not shown), which will throw the exception under the correct circumstances.
If the name field is empty then the validator will throw an exception with the error message "User has no name".
Firstly, two steps must be written. A step to add the user without a name and a second to return the error message.
Step to add invalid user
The user data is passed in as a dynamic, then the properties are assigned to an AddUserModel, which is what is passed to the AddUserRequest. The AddUser method on the administration engine is called and the exception remembered in the test context. Note that this exact step could also be used in a test to check that a user can not be added without an age assigned.
Step to verify exception
The exception is recalled from the text context and verified to ensure it matches the expected error message that is passed into the step. This step is highly reusable as can be used with any test that checks to see the return error message.
Now the steps are in place, the scenario can be written.
Finally, a simple rule is written in the AddUserValidator (not shown), which will throw the exception under the correct circumstances.
If the name field is empty then the validator will throw an exception with the error message "User has no name".
Comments
Post a Comment