Interview Questions

Why Not Just Write a main() Method for Unit Testing?

JUnit Questions and Answers

(Continued from previous question...)

Why Not Just Write a main() Method for Unit Testing?

It is possible to write a main() method in each class that need to be tested for unit testing. In the main() method, you could create test object of the class itself, and write some tests to test its methods.

However, this is not a recommended approach because of the following points:

  • Your classes will be cluttered with test code in main method. All those test codes will be packaged into the final product.
  • If you have a lots of classes to test, you need to run the main() method of every class. This requires some extra coding effort.
  • If you want the test results to be displayed in a GUI, you will have to write code for that GUI.
  • If you want to log the results of tests in HTML format or text format, you will have to write additional code.
  • If one method call fails, next method calls won?t be executed. You will have to work-around this.
  • If you start working on a project created by some other team in your organization, you may see an entirely different approach for testing. That will increase your learning time and things won?t be standard.

Above are some of the problems, which will be taken care of automatically if you use Junit. Junit provides a standard framework for writing your tests. It separates test code from project code, hence keeps everything clean.

(Continued on next question...)

Other Interview Questions