liveBook · Manning

Test-specific subclass

As explained in Test Driven: Practical TDD and Acceptance TDD for Java Developers

A test pattern that creates a subclass to expose or modify behavior or state for testing.

A test-specific subclass exposes or changes internal state or behavior so code can be tested when the original class cannot be modified. It can help when working with legacy code that is difficult to test directly. section 4.5.3

Testing without a merchant service

Suppose billing code uses a credit-card processing class whose validation also contacts a merchant service. If the class belongs to another team and cannot be changed, create a subclass that overrides cardIsActive to always return true. The test then uses a partially stubbed processor rather than contacting the service for that check. section 4.5.3

public class CreditCardProcessing {

    public boolean isValid(String cardnumber) {
        return validationCodeMatches(cardnumber)
                && cardIsActive(cardnumber);
    }

    protected boolean validationCodeMatches(String cardnumber) {
        // validation logic omitted for brevity...
    }

    protected boolean cardIsActive(String cardnumber) {
        // access to merchant system's web service
        // omitted for brevity...
    }
}

See how isValid combines number validation with the protected cardIsActive method that the test-specific subclass can override. section 4.5.3

How Test Driven: Practical TDD and Acceptance TDD for Java Developers covers it

How deep it goes
Defines the pattern and explains a behavior-modifying override, without showing the subclass implementation.
Examples
Uses a credit-card processor whose cardIsActive method contacts a merchant service.
What you can do after
Understand how an override can replace a service-dependent behavior during a test.
How it connects
Connects the pattern to test-driven development, partial stubbing, and the Single Responsibility Principle.

This explainer was generated by Manning's knowledge graph from the text of Test Driven: Practical TDD and Acceptance TDD for Java Developers. The section links point to the parts of the book it draws on.