mardi 1 octobre 2019

How should I test classes with methods that call each other?

Sorry for the vague, beginner question.

Let's say there is a parent class called Parent with a structure similar to:

public class Parent {
    public boolean validateOne(Request req) {
        ...
    }
    public boolean validateTwo(Request req) {
        ...
    }

}

Let's say there are children classes, each with their own validate method which calls the parent validate method.

public class ChildOne {
    public boolean validate(Request req) {
        if (validate1(req)) {
            ...
        }
        ...
    }
}
public class ChildTwo {
    public boolean validate(Request req) {
        if (validate2(req)) {
            ...
        }
        ...
    }
}

Now, I want to test this group of classes, but I'm not sure what the best practice is.

  1. I could test Parent's validateOne() and validateTwo() methods. But I would either need to A) Repeat these tests when testing the children's validate() methods making the parent test cases obsolete or B) I would omit these tests for the children, creating what I feel are incomplete test cases. And if I omit these tests for the parent validate, then if someone in the future refactors the code and completely misses this validation step, my tests wouldn't catch that.

  2. I could just create test cases for the children, but if multiple children share the same validateX() method from the parent, then I would be repeating tests and not following DRY code (Does DRY code even apply to unit tests?)

  3. I could create a test class for the parent and call the parent test class in the children test classes, but it looks like people generally disapprove of that as seen by the third answer here.

Option 3 makes most sense to me, but is there a best option and why? I feel like the answer should be obvious since this is a common case, not just with parent/child classes, but I was never explicitly taught what was best.

Aucun commentaire:

Enregistrer un commentaire