JUnit tutorial, how to create a test class in Eclipse IDE part 1

JUnit tutorial, how to create a test class (test case) in Eclipse IDE.

Why JUnit? What is it good for? When you write some code, you must test it. You usually test it on-the-fly, or you create a main method, where you test your code. But you just did one-time testing and such testing is useless in the long run. Usually customers have nasty habit of changing their requirements and as a result your applications  grow and change over time. Testing then becomes more and more difficult. JUnit is a framework, that offers standardized testing.

Here I have some method I want to test. This method has following input: field, where is date, integer and date pattern. Using provided date pattern this method will format date into String, add some other stuff and return resulting String. I will test this method using JUnit. In order to do that I must add JUnit to classpath, create a test class and implement a test, that will test this method.

Don't bother about adding JUnit to classpath, any decent IDE has JUnit support and will do it on-the-fly. But before creating a test class, it's best practice to create a new source folder dedicated just to tests. Right click your project, Properties, choose Java Build Path, Source, Add Folder, Create New Folder and type name "test".

Now we will create a test class. Right click your class and choose New, JUnit test case and here you can choose several options. Choose all of them, I will explain them later. Change source folder to "test". Click Next. Here you can select methods for which you will create tests. Click Finish and if you didn't do this operation before, Eclipse will ask you if you want to add JUnit library to classpath. Click OK.

Eclipse generated a method stub with calls a method fail with String parameter "Not yet implemented". To run JUnit right click, Run As, JUnit test. This test failed with message "Not Yet implemented". In the next screencast I will show you how to implement this test.