xuongrong
xuongrong

Reputation: 73

Two public method calls a private method

I heard some one said that it's better to write Junit test for a private method via a public method. But in this case, I should test private method to avoid the duplicated code. Is it good approach?

Upvotes: 0

Views: 397

Answers (2)

John B
John B

Reputation: 32949

So, yes you can and a lot of people do test what would normally be private methods in this way. Generally the method is changed to default scope and I recommend adding the @VisibleForTesting annotation provided by Guava.

The problem with this approach is that it does not allow for (or limits the ability of) the code under test to be refactored. A good unit test allows the entire class under test to be completely refactored (while maintaining the same API) without the test failing.

So there is a balance here. Since both public method have the same set of requirements regarding what is happening in the private method it is good practice to fully exercise this set of requirements for each public method.

My suggestion (depending on and balanced by the complexity of the private method) is to create a utility method in your test that configures the private method (sets it up to behave a particular way) and use this method in the tests of the public methods. Do the same for a verify method.

Another option is to create tests that test the private method's functionality and pass in a reflection Method as the entry point. This would allow you to test all functionality via both public methods without repeated code.

Upvotes: 0

dutt
dutt

Reputation: 8209

This is a mix of subjective taste, best practice I've picked up and gut feeling.

For unit tests I don't mind calling private functions directly, if you by unit testing mean test a specific function and nothing else. I don't mind because it cuts down on wrapper code and it's likely that function usage patterns might be rather unusual compared to production code.

If the testing goes further than that, a whole class or a range of functions, I prefer to only use public methods since that's how other code will be using it.

Upvotes: 1

Related Questions