Where to Place Multiple JUnit Test Methods in Code

javajunittesting

I've just read the Vogella JUnit tutorial and found it very helpful in understanding how to use JUnit. However, I'm a bit confused about what the convention is for placing multiple test methods in code. The tutorial only places one test method in a class, then describes how you can use a test suite to group multiple test classes together.

Does this mean that it's common practice for each test class to only have one test method and then test suites are used to chain them together? Or was that just unintended and instead common practice is to put multiple test methods in a class?

Best Answer

It is absolutely common practice to have multiple test methods in a class.

JUnit methods are usually invoked via reflection by collecting all methods in a class (or, as you say, in an entire suite), not by a human application programmer choosing methods from a well-defined API. Therefore, there is no point in keeping each individual test class short or readable; people aren't supposed to understand a class that holds unit tests as a cohesive unit in the same the way that a class of production code should be cohesive. Having one class per test just puts unnecessary strain on your file system (dealing with thousands of files in a directory is often non-linearly expensive).

Related Topic