JUnit4 - First Steps
(Free Web Tutorial)
by Michael Thomas
JUnit Home Page
In this tutorial you will install JUnit, create your
first Java Project using JUnit and discuss TDD.
This tutorial covers:
JUnit Version within Eclipse Neon.1: JUnit
v4.12.0 (as of 10/25/2016)
For reference: JUnit web site latest: JUnit v4.12.0
Updated 04-Dec-2014
Install file: <Use the one built into Eclipse>
Optional Download: Click ( MyJUnit4FirstSteps.zip
) to download a zip of the final files in the Eclipse workspace.
Prerequisites
- JDK installed.
- Eclipse installed.
- This tutorial has been tested in the following environment:
Date: 10/25/2016;
OS: Win 10;
JDK: "1.8.0_111-b14"
Eclipse: Eclipse Neon.1 (as of 10/25/2016)
Objectives
- Add the JUnit JAR to the Eclipse Library
- Create your first Java Project using JUnit
- Write JUnit test cases using assertions
- Learn how to use TDD (Test Driven Development) for all your
Java projects.
Terms
FYI - Possible Errors:
JUnit Install
- Prerequisites - have JDK & Eclipse installed.
- Download JUnit - if needed.
- Note: Eclipse should have JUnit installed!
- Continue with tutorials without downloading unless you
find you need it.
Skip the download!
- For reference only
http://junit.org
- Double Click the "Download and Install" tab at the top
to go to the main download page.
- Under "Plain-old JAR" click on "junit.jar"
- As of 10/25/2016 the following is the latest stable
release:
v4.12 Updated 04-Dec-2014.
- In the "Download" column right click on the "jar" link
and choose "Save target as".
Warning: Your browser may change the extension to
.zip. If so change it back to .jar.
- Notes on the files:
- jar - the junit jar file to install.
- javadoc.jar - the Java Docs
Overview
- In TDD (Test Driven Development) you create test methods in a
JUnit test class as you are creating methods in the implementing
class.
The test class will have methods that test out all the exposed
methods in the implementing class.
- The Specs: For this simple
example, the specs give to us is to create the following exposed
methods using a TDD approach.
- int myMethodInt(int) - if parm is <= 10 return 0 else 1.
- double myMethodDouble(double) - return 10% of what is
passed.
- boolean myMethodBoolean(boolean) - if parm is true return
true else false.
- String myMethodString(String) - if parm = "Hello World"
return "You won!" else "No".
- public boolean goodHouseLoanRate() - If loan rate is <=
3.0 return true else false.
- In small iterations we will "Fake it, then Make it!"
We create a fake method in the implementing class that returns
the correct answer to the testing method in the JUnit class.
Once test is good (green) then we make the real code and test
until green again.
Create a Java Project
- Create a test Java Project
- File, New, Project
- Click "Java Project", then Next
- Project name: MyJUnit4FirstSteps
- Add the JUnit4 library to your Java Project.
- Right click on the Java Project (MyJUnit4FirstSteps),
Properties, Java Build Path, click the "Libraries" tab.
- Click "Add Library", JUnit, Next, then choose JUnit4
for the "JUnit Library Version".
- Click "Finish", "Ok".
- Notice that Eclipse has created a "src" folder that you will
place the implementing classes in.
- Create a new "source folder" to place all the JUnit test class
files in.
- File, New, Source Folder: test
- Click "Finish"
- Note: This will allow you to keep your test code
in a separate directory (source folder) but have access to package-private
data members (methods & variables) in the classes we
will place in the same package in the "src" source folder.
Create our JUnit Test Java Class
- Create a Package in the "test" source folder.
- Right click on "test", New, Package: junit.learnnow
- Create a "JUnit Test Case" class
- Right click on the "test"
package name "junit.learnnow" and choose "New", "JUnit Test
Case"
- Screen: JUnit Test case
- Source Folder: <leave default>
- Package: <leave default>
- Name: MyClassTest
(Notice: Always use the <class name> followed by
"Test" for the test classes name)
We will later create the MyClass class.
- Superclass: <leave default>
- Which methods to create?
Check: setUpBeforeClass()
Check: setUp()
Check: tearDownAfterClass()
Check: tearDown()
- Do you want to add comments?
Check: Generate comments
- Class under test: <leave blank>
- Note for reference: If "MyClass" happened to already
existed you can have the wizard generate the JUnit test
class.
- In that case you would use the following option on
the screen.
Class Under Test: MyClass
- Click "Next", and you will be prompted to check
the class & methods you want to test.
- Click "Finish"
- If you did not add the JUnit Library earlier you
might get the prompt "JUnit 4 is not on the build
path. Do you want to add it?" click "OK".
- MyClassTest.java - you just created this file!
- Notice the following:
- Imports - Notice the imports that was generated.
import static
org.junit.Assert.*;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
- Class Name - always follows the naming convention:
<ClassName>Test
ie: MyClassTest
- Java Notation - using a Java notation of @Test before
all test methods.
- Test Methods - all methods that you want JUnit to run
will follow these rules:
- Visibility is: public
- Return type is: void
- Arguments: None!
- Method names start with lower case "test"
- WARNING: The order of
running the methods can NOT be predicted! Do not
make test cases that rely on other methods running
first!
- Run the JUnit Test
Create our Implementing Java Class
- Create a Package in the "src" source folder.
- Right click on "src", New, Package: junit.learnnow
- Create a class
- Right click on the "src"
package name "junit.learnnow" and choose "New", "Class"
xxx "JUnit Test Case" - Name: MyClass
Use defaults for the other options.
Development Process Overview
- Best Practice for TDD
- Initially create a test method in the JUnit class for all exposed methods you plan to create in your implementing class.
Have each test method initially call the method: fail("Not yet implemented");
- In small iterative cycles do the "Fake it, then make it!" steps.
- Fake it, then Make it!
- In the development process you want to have small iterations of the following:
1. Add "Fake it" code in the implementing method.
2. Test green in the JUnit method.
3. Add additional JUnit test code. Will probably no longer be green!
4. Add "Make it" code in the implementing method.
5. Test green in the JUnit method.
6. Repeat steps 3 thru 5 until functionality is complete.
Repeat these steps in small iterations.
Development Process Example
- JUnit - fail() (MyClassTest.java)
Create initial fail() methods in the JUnit class for all exposed methods in the implementing class.
- Fake it! (MyClass.java - Implementing)
- Test it! (MyClassTest.java - JUnit)
- Add this code:
@Test
public void testMyMethodInt() {
System.out.println("running testMyMethodInt()");
MyClass c1 = new MyClass();
assertEquals(0, c1.myMethodInt(0));
}
- MyClassTest.java.code03.txt
- click to view the example source code.
- Run as JUnit
Notice that in the JUnit panel "testMyMethodInt" is now green!
You have faked it and it tests green!
- Add additional testing code! (MyClassTest.java - JUnit)
- Add this code:
@Test
public void testMyMethodInt() {
System.out.println("running testMyMethodInt()");
MyClass c1 = new MyClass();
assertEquals(0, c1.myMethodInt(0));
assertEquals(0, c1.myMethodInt(10));
assertEquals(1, c1.myMethodInt(11));
assertEquals(1, c1.myMethodInt(100));
assertEquals(0, c1.myMethodInt(-1));
}
- MyClassTest.java.code04.txt
- click to view the example source code.
- Run JUnit!
No longer green!
In the JUnit panel click on "testMyMethodInt" to see where the first test fails.
- Make it (MyClass.java - Implementing)
- Test it! (MyClassTest.java - JUnit)
- testMyMethodInt - should now have a green check mark!
Complete the Project
- Following the TDD process complete the other 4 methods in the JUnit and implementing classes.
- You should end up with the following in the JUnit panel.
Bar should be fully green.
All methods should be green.
Runs: 6/6
Errors: 0
Failures: 0 - Here is an example of the final source code.
Additional Projects/Labs
- Lab 1: Build a JUnit and implementing class that tests a file IO.
Sample Solution:
- JUnit (MyFileTest.java)
MyFileTest.java.txt - click to view the example source code. - Implementing class (MyFile.java)
MyFile.java.txt - click to view the example source code.
General JUnit Test Case Info
- Red bar - tests fail.
- Green bar - all tests pass.