JUnit is a framework used to created tests in Java projects.
Installation
If we have Eclipse, it is not necessary to install it, because it is included. If we are not using an IDE, we have to download from its Web page (https://github.com/junit-team/junit4/wiki/Download-and-Install).
Creation of a new project
In Eclipse, we go to New Project / Java Proyect. We give a new name to the new project, and in the “Java Settings” screen, we have to inform that we are going to use the JUnit testing library. We click on the “Libraries” tab and on “Add Library…”. We select “JUnit” and “JUnit 4” version.
Java classes generation
First we need code to launch tests on it, so we create a small class with one method that returns a text string.
MyObject.java
package app; public class MyObject { public String myMethod() { return "myString"; } }
JUnit test class generation
Now, we create a new class, but this time is not a “Class” type, but a “JUnit Test Case”.
Test method annotations
JUnit 4 brings several annotations to mark the methods that will be executed when launching the test (they will be used to lauch code before or after the tests or in first or last place when the test object gets instancied), but here we will only use @Test, that is used to mark methods as JUnit4 tests.
Test creation
In this test class, we create a method (with an autoexplicative name) and we use the instruction “assertEquals” to compare what it returns against what we expect it returns.
There are a lot of Assert types. Among them we can find “assertNotNull” or “AssertTrue”, that respectively compare that the tested object is not null and that it is True.
MyObjectTest
package app; import static org.junit.Assert.*; import org.junit.Test; public class MyObjectTest { @Test public void testMyMethod() { MyObject myObject = new MyObject(); assertEquals(myObject.myMethod(), "myString"); } }
Test execution
In order to execute a class with tests, we right-click on the name of the class in the Project explorer, and we click on “Run As…/JUnit test”.
We will see the JUnit with the test result and a green bar if successful, or red if failure.
Repository
The code of this demonstration can be located at https://github.com/luisgomezcaballero/junit4-demo.
So, what do you think ?