Skip to content
Advertisement

JUnit – How many files for testing a single class?

Let’s say I have a class MyClass.java and we have to write a tests for it. Some of them will execute once, some of them will execute multiple times.

  1. I prepared two test classes – MyClassTestSingle.java for single tests and MyClassTestMultiple.java for tests with @Parametrized annotation.
  2. I wanted to run them from a single file so there is another class – MyClassTestSuite.java.
  3. In MyClassTestSingle.java and MyClassTestMultiple.java methods I use same parameters with a same values so i started thinking about a class containing these parameters…

But then I realized I wanted to create four classes for testing a single class. So I started looking for some “good practices” how to keep my test classes clean and simple. But found no worthy informations about number of classes I need when writing tests for a situation above.

I started thinking that maybe there is a design problem in my MyClass.java, but for sure there are situations when there is need to make a parametrized and single tests and then pack them into a suite.

Am I wrong? Or maybe I just don’t understand something?

Advertisement

Answer

There is no “right” or “wrong” way here. However there are some conventions.

First, typically test cases names are typically ended by Test. Typically we implement test case per class and name it after the production class with Test suffix. Follow this convention and various build and reporting tools will work for you automatically without additional configuration.

Splitting test case to several classes can be used if it is needed. For example when number of tests or number of code line exceeds reasonable limit or if there are some test groups that should be maintained separately. Your example (parameterized and not parameterized tests) sounds like reasonable case.

So, I’d create MyClassSingleTest.java and MyClassMultipleTest.java.

Variants: MyTest.java and MyTestParameterized.java.

Probably a good idea to give more meaningful name. Try to express what do your parameters mean. For example UserParameters, DbParameters etc. In this case call your parameterzied class MyClassUserTest.java or something like that.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement