sonicboom
sonicboom

Reputation: 5028

Should I unit test validation code? It seems impractical

I'm learning test driven development and I want to know what I should I do when it comes to test driving validation. Should I create unit tests that test every possible combination of validation outcome? That seems practically impossible when dealing with large entities. Say I have a model entity with lots of attributes, some with constraints, as follows -

@entity
public class MyClass extends Model {

    @Constraints.Required
    @Constraints.MaxLength(20)
    public String attribute1;

    @Constraints.Required
    public String attribute2;

    public float attribute3;

    @Constraints.Required
    public String attribute4;

    @Constraints.Required
    public String attribute5;

    @Constraints.Max(100)
    public int attribute6;

    @Constraints.Required
    public String attribute7;

    ...
    ...
    ...
}

So I be writing unit tests for validating such an entity or is that pointless? I can run it through a Validator function and get the number of failed validations...but if I'm being strict about testing wouldn't I have to do it for all possible combinations of invalid attributes, which would entail creating a massive amount of instances to test.

So it definitely seems pointless in this case, and wouldn't that imply that unit tests are pointless for any entity validation? I.e. if they are pointless for an entity with a lot of attributes they must also be pointless for an attribute with only a few attributes?

Upvotes: 1

Views: 373

Answers (1)

Carl Manaster
Carl Manaster

Reputation: 40356

I would test, not with every possible combination, but each attribute constraint. So create a valid entry, check that there are no failures. Change one thing from that entry in such a way as to violate a particular constraint; ensure that that constraint catches it. Repeat with each constraint. Now you know the constraints are all working.

Upvotes: 3

Related Questions