Free tutorials for Java, Eclipse and Web programming



Unit testing with JUnit 4.x and EasyMock in Eclipse - Tutorial

Lars Vogel

Version 1.0

06.12.2009

Revision History
Revision 0.1-0.503.09.2007Lars Vogel
JUnit description
Revision 0.610.05.2008Lars Vogel
Added EasyMock
Revision 0.725.11.2008Lars Vogel
Small updates, add @Ignore and update Test Suites to JUnit 4.x.
Revision 0.802.02.2009Lars Vogel
Added how explanation how to easily add static imports
Revision 0.910.10.2009Lars Vogel
Fixed broken link for JUnit download
Revision 1.006.12.2009Lars Vogel
Reworked, simplified, updated screenshots

Unit testing with JUnit and EasyMock

This article explains unit testing with JUnit 4.x and Easymock within Eclipse. The creation of a test using the the new annotations in JUnit 4 are explained and the creation of JUnit 4 test suites. EasyMock is used to emulate objects to enable JUnit to test each object in isolation. Sample code is provided.


Table of Contents

1. General
1.1. Unit Testing
1.2. Installation
2. JUnit with Eclipse
2.1. Preparation
2.2. Create a normal class
2.3. Create a test class
2.4. Create a test suite
3. JUnit (more) in Detail
3.1. Static imports with Eclipse
3.2. Annotations
3.3. Assert statements
4. Easy Mock
4.1. Easy Mock Overview
4.2. Using Junit and Easy Mock
5. Thank you
6. Questions and Discussion
7. Links and Literature
7.1. Performance

1. General

1.1. Unit Testing

A unit test is a piece of code written by a developer that tests a specific functionality in the code which is tested. Unit tests can ensure that functionality is working and can be used to validate that this functionality still works after code changes.

JUnit 4.x is a test framework originally written by Erich Gamma and Kent Beck. It uses annotation to identify the test methods.

JUnit assumes is that the all test can be performed in an arbitrary order. Therefore tests should not depend other tests.

JUnit uses annotations to identify which methods should be used for testing.

To write a test

  • Annotate a method with @org.JUnit.Test

  • Use a method provides by JUnit to check the expected result of the code execution versus the actual result

JUnit uses frequently static imports. Static imports are available since Java 5.0: static import, e.g. import static org.junit.Assert.*;

The following assume that you are using Eclipse as development environment.

1.2. Installation

Tip

Eclipse has JUnit already included, therefore if you intend to use JUnit within Eclipse you don't have to download anything.

Download JUnit4.x.jar from the JUnit website . The download contains a "junit-4.*.jar" which is the JUnit library.

To make JUnit available in your Java project you have to add the the JUnit library file to your Java classpath.