This post is the second in the series of posts regarding implementing Mspec for unit tests within TDD. This section looks at how tests can be written to check that the correct exceptions are thrown under certain conditions. An understanding of Test-driven development (TDD) with Mspec - Part 1 is assumed.
The test shown here will cover the throwing of a validation exception when a user is added without a name. New users are added using an AddUserModel, which is shown below. Note that the Required tag is appended to both the Name and Age properties.
In the post method in the user controller, first the model state is checked to ensure it is valid. If the model is not valid (i.e if there is no value for either the age or name, or both) a validation exception is thrown.
Below, the ValidateModel method cross-checks the property values on the model with any associated validation attributes, for instance the Required attribute. If there is an invalid property value then the ModelState.IsValid in the controller shown above will return false and hence the validation exception will be thrown and the test will pass.
The test shown here will cover the throwing of a validation exception when a user is added without a name. New users are added using an AddUserModel, which is shown below. Note that the Required tag is appended to both the Name and Age properties.
In the post method in the user controller, first the model state is checked to ensure it is valid. If the model is not valid (i.e if there is no value for either the age or name, or both) a validation exception is thrown.
In the test an AddUserModel is created with a null name in the Establish step. Then, in the Because step the result is set to the output of the post method. However, first the ValidateModel method is called, which is located in the WebApiDataAnnotationsValidator (shown later). Finally, in the It delegate the exception type is verified. If a validation message was used this would also be checked - but not included here for brevity.
Below, the ValidateModel method cross-checks the property values on the model with any associated validation attributes, for instance the Required attribute. If there is an invalid property value then the ModelState.IsValid in the controller shown above will return false and hence the validation exception will be thrown and the test will pass.
Comments
Post a Comment