Is it ok to put a main() function in all modules for the purpose of unit tests?

I have several subclasses to go along with my main class. Is it bad practice to add a main function to every single class for tests?

Jon Skeet
people
quotationmark

Is it bad practice to add a main function to every single class for tests?

Yes, for various reasons:

  • It suggests you've got a single test per class, or multiple tests within a single method.
  • It suggests you're probably not using a unit test framework, with all the built-in helpers (and runners) available
  • Combining your test code and your production code makes it harder to find your tests and harder to read your production code.

Typically, I use a separate Eclipse project in the same package (for access to package-restricted members), using JUnit or something similar.

people

See more on this question at Stackoverflow