0
0
JUnittesting~5 mins

Testing private methods (should you?) in JUnit - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is a private method in Java?
A private method is a method that can only be accessed within the class it is declared in. It is hidden from other classes to protect internal implementation.
Click to reveal answer
beginner
Should you test private methods directly in JUnit?
Usually, no. Private methods are tested indirectly through public methods that use them. Testing private methods directly can break encapsulation and make tests fragile.
Click to reveal answer
intermediate
How can you test private methods if absolutely necessary?
You can use reflection to access private methods in tests, but this is discouraged because it makes tests harder to maintain and breaks encapsulation.
Click to reveal answer
intermediate
What is a better alternative to testing private methods directly?
Refactor the code to move complex logic into package-private or public helper classes or methods, so they can be tested directly without breaking encapsulation.
Click to reveal answer
beginner
Why is testing private methods directly considered a bad practice?
Because it tightly couples tests to the internal implementation, making tests fragile and harder to maintain when the code changes internally but behavior stays the same.
Click to reveal answer
What is the recommended way to test private methods in Java using JUnit?
ATest them indirectly through public methods
BUse reflection to call them directly
CChange their access modifier to public
DIgnore testing private methods
Which of the following is a risk of testing private methods directly?
ATests are easier to write
BTests run faster
CTests become tightly coupled to implementation details
DTests cover more code
What Java feature can be used to access private methods in tests, though it is discouraged?
AAnnotations
BInheritance
CInterfaces
DReflection
If a private method contains complex logic, what is a good practice?
AMake the private method public
BRefactor the logic into a separate class with public methods
CSkip testing that logic
DDuplicate the logic in the test
Why might changing a private method to public just for testing be a bad idea?
AIt exposes internal details unnecessarily
BIt improves encapsulation
CIt makes the code run slower
DIt reduces code coverage
Explain why testing private methods directly is discouraged and how you should test their behavior instead.
Think about how private methods relate to the class's public interface.
You got /4 concepts.
    Describe how reflection can be used to test private methods and why it is generally not recommended.
    Reflection is a powerful tool but can cause maintenance issues.
    You got /4 concepts.