Biscuit128
Biscuit128

Reputation: 5408

Unit Testing with JUnit

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

Answers (3)

mikera
mikera

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:

  • Recognise that the method really should be part of the public interface and make it public
  • Write a test against some existing public methods of the class that indirectly test the private method
  • Write a new public method that exposes the behaviour you wish to test
  • Refactor the behaviour out into another class which you can test (thanks Tom for the extra idea!)

Upvotes: 4

sinharaj
sinharaj

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

esaj
esaj

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

Related Questions