Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Junit Best Practice: Public method calling multiple private methods

I am starting to write JUnit test cases for a legacy codebase. One of the public methods has multiple if statements and based on a condition it is calling different private methods.
Should I write just one test method and test for all the conditions? or one method for each condition?

Wouldn't I lose consistency if I write individual methods for each if condition?

What is the approach to test private methods? Private method logic could be more complicated than public methods.

like image 959
Himanshu Yadav Avatar asked Apr 05 '13 19:04

Himanshu Yadav


2 Answers

Base the number of methods on the number of scenarios you want to test, it has nothing to do with the methods that the thing being tested has.

If each scenario takes its own code to set up, then you will get one test method for each scenario. If you can parameterize the tests then you may be able to have one test method and pass in different data for each scenario.

The important thing is that for each combination of inputs you want the test to succeed or fail independently of the other tests. If you shoehorn all the tests into one method then that can't happen, the first test failure will prevent the remaining tests from running.

like image 54
Nathan Hughes Avatar answered Nov 07 '22 11:11

Nathan Hughes


I agree with Nathan. Tests should go by scenarios not methods. Sometimes legacy code is written in a way that you need to test private methods directly though. And yes, the code should be refactored. But if you can't refactor or want a test in place first...

Option 1 - make methods package private access

This is a very safe refactoring.

Option 2 - use reflection to call the static method directly

If you REALLY can't touch the code, this is the best you can do. I'd question the requirement to not touch the code. If we can't improve the code, should we leave it in the corner to rot?

like image 26
Jeanne Boyarsky Avatar answered Nov 07 '22 13:11

Jeanne Boyarsky