Reputation: 5408
As i understand it, the correct way to test private methods is via reflection? So if we test a method via reflection, we need to make an instance of the class, get the method, invoke it and so on. However, what do we do if the class that we create uses data from other objects that will return null / be null without the correct previously made objects.
Thanks
Upvotes: 1
Views: 155
Reputation: 106401
I personally think you should avoid writing tests on private methods. Using reflection to me is a design smell - you should ideally write tests only against the exposed public interface of your class.
If you feel the need to test a private method, then this suggests to me that you should do one of the following:
Upvotes: 4
Reputation: 1103
You can use an existing instance of the class (say, the instance on which you've already tested the public methods).
Now just invoke the private method (found through reflection) of that instance, which, presumably, must have all the 'previously made' objects.
Upvotes: 1
Reputation: 16035
As i understand it, the correct way to test private methods is via reflection?
It's the only way (if you're only testing the private method, and not some other public method that calls the private method), as you cannot access the private methods from outside of the class (except with reflection). I don't usually write separate tests for private-methods, but it can be useful.
what do we do if the class that we create uses data from other objects that will return null / be null without the correct previously made objects.
In unit-tests, you "mock" the outside dependencies, either using a mocking-library, such as Mockito or some other, or write anonymous or separate mocking classes implementing the interface of the dependency. The idea is that you define some exact behavior for the outside dependencies, so their behavior won't affect the testing of the actual class. If the fields holding the references are private, you need to use reflection to inject the objects into them.
In integration-testing, you use the actual implementations of the outside dependencies.
Upvotes: 3