In order to make sure that the TeamMentor server only creates users with valid data, here is how I implemented data validation into the NewUser class using .NET's DataContract annotations.
The first step was to add the annotations to the NewUser object, which originally looked like this:
And like this after adding the the DataContract, DataMember, Required, StringLength and RegularExpression attributes:
At it stands, this doesn't do anything , since the ‘DataContract’ is not enforced by anybody (they are 'just' attributes on a class)
At the moment, all the UnitTests are passing (see below why this is relevant):
Before we add the validation to the main codebase, lets create a number of tests to make sure the validation behaving as it expected.
UnitTest: Validation_NewUser_RequiredFields:
UnitTest: Validation_NewUser_LargeDataInFields:
UnitTest: Validation_Email_Format:
Now that we have the UnitTests confirming that the validation is working as expected, let’s run all tests again and double-check that all is good (note that there are 4 more tests):
Adding the check to the main Codebase
Next step is to add the validation requirement to the method called by the exposed WebService Methods (this will enforce the DataControl rules into every new user request made to TeamMentor):
And, as I was expecting , this will break a number of tests (that passed when there was no validation in place)
Namely the tests that create test users (and check the new user account creation workflow):
Most of the errors where caused by the use of this helper method:
Which needs to be updated to:
With this change, the tests in this class will pass again (note that all failed before the change shown above):
After a couple more changes we have all the Unit Tests back in action.
Time to push into GitHub,
So that TeamCity can re-execute the tests and publish the new version to the test server :)
NOTE: ExtensionMethods
Here are the extension methods I created that help to hide the complexity of the DataAnnotations class
ExtensionMethod Signatures:
ExtensionMethod’s code: