Reputation: 11499
I need check with junit that method of nested anonymous class invoked. But this class is private. Does there exist a way to test it without changing visiblity and logic of work? It may be that a common way exists to resolve similar problems?
Upvotes: 3
Views: 2174
Reputation: 2722
I quite agree with Matthew Farwell when he says:
In general, your tests should not be depending upon implementation details, but should be testing behaviour, not the specific implementation.
However, tests call out for good design. If you really feel you should test that class directly, then that's a hint that that class should be a normal public class (and not an inner anonymous).
Upvotes: 1
Reputation: 522
You should not test that private class directly.
Most likely it's just a small class used as a util or it implements some broad, public interface.
In the first case just test class that wraps up the private class, and don't worry about private one at all. You can treat it as an implementation detail.
In second case just test that class against it public interface.
If I'm wrong about your code, then my advise would be to change design a bit, move wrapper class into separate package, extract private class to package level and test it directly. Last way would be to mark it as @VisibleForTesting (annotation from Guava library) and raise visibility to package private (default).
Upvotes: 1
Reputation: 61705
The fact that the class is private or anonymous means that the implementation details are private. In general, your tests should not be depending upon implementation details, but should be testing behaviour, not the specific implementation.
Upvotes: 6
Reputation: 198211
The only way is to test the method that creates the object of the anonymous inner class, or to make it non-anonymous and non-private. (I've seen a fair amount of code that makes it default-visibility and uses a @VisibleForTesting
annotation.)
Upvotes: 2