1

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 in the children classes, then if someone in the future refactors the code and completely misses this parent 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. And although the example provided in that answer directly answers my question, it's unclear how I should proceed if the classes have no parent-child relationship.

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.

Azianese
  • 291
  • 3
  • 13

1 Answers1

0

It seems the best thing to do is to either mock the behavior of the parent method (if the method makes a significant impact on the child method's output) or check whether the parent method was called and proceed from there.

Azianese
  • 291
  • 3
  • 13