Video in progress
Should you make a private method `public` or package-private in order to test it?
Usually no. A private method is tested through the public methods: tests should check behavior, not internal structure. If testing a private method on its own feels really necessary, it usually means it should be extracted into a separate class.
📖 Answer
The situation: InvoiceService has a 60-line private calculateTax(...) and you want to test it on its own.
Opening it up (package-private with @VisibleForTesting) is the quick way, but:
- the test gets tied to the internal structure: if you split the method or rename it, the test breaks even though the behavior didn't change;
- other code starts calling the method too: nobody reads a comment saying "for tests only".
The better way is to extract the concept:
public final class TaxCalculator { // separate, independent, pure
public Money taxFor(Money amount, TaxRegime regime) { ... }
}
@Service
class InvoiceService {
private final TaxCalculator taxes;
...
}
Now TaxCalculator has its own public API and you can test it freely. The InvoiceService test then only checks the whole flow.
When I leave a private method alone: when it's a 5–10 line helper and the tests of the public methods cover all its branches. The coverage report shows this.
Calling a private method with reflection (setAccessible(true)) is the worst option: the IDE won't find it during refactoring, and the test breaks silently.
There is an exception for legacy code: if you need a safety net before refactoring, it's fine to open the method temporarily and write a characterization test, with a plan to close it again afterwards.
Sign up to mark studied questions and save your progress.