Free tutorials for Java, Eclipse and Web programming



Follow me on twitter

JUnit - Tutorial

Lars Vogel

Version 1.3

06.02.2011

Revision History
Revision 0.1-0.503.09.2007Lars Vogel
JUnit description
Revision 0.6 - 1.310.05.2008 - 06.02.2011Lars Vogel
bugfixes and enhancements

Unit testing with JUnit

This tutorial explains unit testing with JUnit 4.x. It explains the creation of JUnit tests and how to run them in Eclipse or via own code.


Table of Contents

1. Introduction
1.1. Unit Testing
1.2. Unit Testing with JUnit
1.3. Installation of JUnit
2. JUnit with Eclipse
2.1. Preparation
2.2. Create a Java class
2.3. Create a JUnit test
2.4. Run your test via Eclipse
2.5. Run your test via code
3. JUnit (more) in Detail
3.1. Static imports with Eclipse
3.2. Annotations
3.3. Assert statements
4. Thank you
5. Questions and Discussion
6. Links and Literature
6.1. JUnit Resources
6.2. vogella Resources

1. Introduction

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.

Unit testing uses also mocking of objects. To learn more about mock frameworks please see EasyMock Tutorial

1.2. Unit Testing with JUnit

JUnit 4.x is a test framework which uses annotation to identify the methods which contain tests. JUnit assumes that all test methods can be performed in an arbitrary order. Therefore tests should not depend other tests. To write a test with JUnit

  • 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

You use a tool like Eclipse or the class "org.junit.runner.JUnitCore" to run the test.

1.3. Installation of JUnit

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. See Eclipse IDE Tutorial to learn how to do this in Eclipse.