I run all my actions through classes that I call "commands". To illustrate this, to create a new user I would call the following code
new CreateUserCommand(unitOfWork).SetName("Username").SetPassword("Blah").Execute();
I am now currently looking at implementing validation into this system, to validate things such as the password is a certain length, the username is not a duplicate in the database, etc...
To handle this, I am looking at using fluent validations and creating a validation class for each type of entity validation entity I want. For example, I would have a class such as
public class NewUserValidation : ValidationFor<User>
{
public NewUserValidation()
{
// Validation Rules here
}
}
One advantage of creating validation in it's own class is that I can use the same validation rules for multiple commands (for example, editing and creating companies may use the same validation rules).
Now each of these validation classes would have unit tests associated with them. However, I am trying to figure out how to deal with the unit tests for the command classes that utilize these validation classes.
For example, when creating a test for the command class, would I create individual tests for each validation rule for the class (thus essentially duplicating all the unit tests for the validation class itself for every command class I plan to use the same validation class for)? This makes a lot of overhead, especially when I already know that the validation class works because of separate unit tests for them.
The only other option that I see is to expose a public property in the command that holds the validation class, and I would then unit test that the command's validation class is the expected validation class. The problem with this method though is I need to devise some way to verify that my Execute()
method is actually running the validation class (otherwise there is no way to know if validation isn't being run).
I am still leaning towards the latter testing method, just to help keep the overhead down, but I do need to find a solution for checking if the validation is actually run. Would this be a bad way to go about it, and would I be better going for the former style instead?
Edit: To reply to both answers below, the validation is going to be used inside of the
Execute()
method, by a validator.Validate(entity)
call in the implementation of Execute()
.
While I don't want to violate DRY, I don't see an easy way to verify that Execute()
1) uses the correct validation class by default and 2) Actually calls the .validate(entity)
method of the validation class.
I can solve #1 by instantiating the validation class in the constructor, and expose it through a public property of the command class, but I am unsure of how to correctly unit test for the 2nd issue without repeating the individual validation unit tests.