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.
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.
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With