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?
✗ Incorrect
Private methods should be tested indirectly through public methods that use them to keep encapsulation intact.
Which of the following is a risk of testing private methods directly?
✗ Incorrect
Directly testing private methods couples tests to internal details, making them fragile.
What Java feature can be used to access private methods in tests, though it is discouraged?
✗ Incorrect
Reflection allows access to private methods but breaks encapsulation and is discouraged for testing.
If a private method contains complex logic, what is a good practice?
✗ Incorrect
Refactoring complex logic into testable public methods improves testability and design.
Why might changing a private method to public just for testing be a bad idea?
✗ Incorrect
Changing access to public exposes internal details and breaks encapsulation.
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.