简体   繁体   中英

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.

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?

From my point of view having smaller units in unit testing normally results in better tests. For you this would mean to change the private methods to package private and to write tests for each of them.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM