Professional Documents
Culture Documents
Lars Vogel
Version 1.4
21.08.2011
Revision History Revision 0.1-0.5 JUnit description Revision 0.6 - 1.4 bugfixes and enhancements 10.05.2008 - 21.08.2011 Lars Vogel 03.09.2007 Lars Vogel
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
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
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.
Download JUnit4.x.jar from the JUnit website . The download contains the "junit-4.*.jar" which is the JUnit library. Add this library to your Java project and add it to the classpath. See Eclipse IDE Tutorial to learn how to do this in Eclipse.
2.1. Preparation
Create a new project "de.vogella.junit.first". We want to create the unit tests in a separate folder. Create therefore a new source folder "test" via right mouse click on your project, select properties and choose the "Java Build Path". Select the tab source code.
Press "Add folder" then then press "Create new folder". Create the folder "test".
The creation of an separate folder for the test is not mandatory. But it is good advice to keep the test coding separate from the normal coding.
return x / y;
Select your new class, right mouse click and select New ->JUnit Test case, change the source folder to JUnit. Select "New JUnit 4 test". Make sure you change the source folder to test.
Press next and select the methods which you want to test.
If you have not yet JUnit in your classpath, Eclipse will asked you if it should be added to the classpath.
package de.vogella.junit.first;
import org.junit.Test;
@Test
Right click on your new test class and select Run-As-> Junit Test.
The test should be failing (indicated via a red bar). This is due to the fact that our multiplier class is currently not working correctly (it does a division instead of multiplication). Fix the bug and re-run test to get a green light.
If you have several tests you can combine them into a test suite. All test in this test suite will then be executed if you run the test suite. To create a new test suite, select your test classes, right mouse click-> New-> Other -> JUnit -Test Suite
Select next and select the methods you would like to have test created for.
This does currently not work for JUnit4.0 testcases. See Bug Report
Change the coding to the following to make your test suite run your test. If you later develop another test you can add it to @Suite.SuiteClasses package mypackage;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
@RunWith(Suite.class)
@Suite.SuiteClasses( { MyClassTest.class })
You can also run your test via your own coding. The class "org.junit.runner.JUnitCore" provides the method runClasses() which allows you to run one or several tests classes. As a return parameter you receive an object of type "org.junit.runner.Result". This object can be used to retrieve information about the tests and provides information about the failed tests.
Create in your "test" folder a new class "MyTestRunner" with the following coding. This class will execute your test class and write potential failures to the console. package de.vogella.junit.first;
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;
System.out.println(failure.toString());
JUnit uses a lot of static methods and Eclipse cannot automatically import static imports. You can make the JUnit test methods available via the content assists.
Open the Preferences via Window -> Preferences and select Java > Editor > Content Assist > Favorites. Add then via "New Member" the methods you need. For example this makes the assertTrue, assertFalse and assertEquals method available.
You can now use Content Assist (Ctrl+Space) to add the method and the import.
3.2. Annotations
Table 1. Annotations
Description Annotation @Test identifies that this method is a test method. Will perform the method() before each test. This method can prepare the test environment, e.g. read input data, initialize the class)
Test method must start with test Will perform the method before the start of all tests. This can be used to perform time intensive activities for example be used to connect to a database
Will perform the method after all tests have finished. This can be used to perform
Annotation
@Ignore
Will ignore the test method, e.g. useful if the underlying code has been changed and the test has not yet been adapted or if the runtime of this test is just to long to be included.
@Test(expected=IllegalArgumentException.class) Tests if the method throws the named exception @Test(timeout=100) Fails if the method takes longer then 100 milliseconds
Statement fail(String)
Description Let the method fail, might be usable to check that a certain part of the code is not reached.
assertTrue(true);
True
assertsEquals([String message], expected, actual) Test if the values are the same. Note: for arrays the reference is checked not the content of the arrays assertsEquals([String message], expected, actual, Usage for float and double; the tolerance are the number of decimals which tolerance) assertNull([message], object) assertNotNull([message], object) assertSame([String], expected, actual) assertNotSame([String], expected, actual) assertTrue([message], boolean condition) must be the same Checks if the object is null Check if the object is not null Check if both variables refer to the same object Check that both variables refer not to the same object Check if the boolean condition is true.
4. Thank you
Before posting questions, please see the vogella FAQ . If you have questions or find an error in this article please use the www.vogella.de Google Group . I have created a short list how to create good questions which might also help you.
Eclipse RCP Training (German) Eclipse RCP Training with Lars Vogel
Git Tutorial Put everything you have under distributed version control system
Lars Vogel
Version 0.4
14.06.2011
Revision History Revision 0.1 created Revision 0.2 - 0.4 bug fixed and enhancements 06.02.2010 - 14.06.2011 Lars Vogel 06.02.2010 Lars Vogel
This article explains testing with the EasyMock framework within Eclipse. It is based on EasyMock 3.0 but should also work on later versions.
Table of Contents
1. EasyMock and Mock Objects Overview 1.1. Testing and Mock Objects 1.2. EasyMock 2. Using Easy Mock and Junit 3. Thank you 4. Questions and Discussion 5. Links and Literature 5.1. Performance
The following is based on an understanding JUnit . In case your are not familiar with JUnit please check the following JUnit Tutorial .
Unit testing is defined as testing classes or methods in isolation. Java classes usually depend on other classes. A mock object is a dummy interface or class in which you define the dummy output of a certain method call. These objects should be provided to the class which is tested. Therefore the class to be tested should to avoid any hard dependency to external data. The classical example is a mock object for a data provider. In production a real database is used but for testing a mock object simulates the database and ensures that the test conditions are always the same.
To unit test your class you need to simulate /control the other classes. The best way is to provide mocks to the class which should be tested. The can either program these classes manually or use a mock framework to simulate these classes.
1.2. EasyMock
EasyMock is a popular mock framework which can be easily used in conjunction with JUnit . The following demonstrates the usage of EasyMock.
Download EasyMock from the EasyMock Homepage and add the easymock.jar to your classpath. You also need to download Objenesis and Cglib and add there jars to your classpath.
Create a new Java Project JavaMockTest. Create the following classes. The class IncomeCalculator should be tested. The class has the purpose to calculate based on the provided method and position the salary of a person. Obviously the test depends on the provided methods. package income;
package income.exceptions;
super(message);
package income.exceptions;
super(message);
package income.method;
import income.Position;
package income;
import income.exceptions.CalcMethodException;
import income.exceptions.PositionException;
import income.method.ICalcMethod;
this.calcMethod = calcMethod;
this.position = position;
if (calcMethod==null){
if (position==null){
return calcMethod.calc(position);
Using Eclipse JUnit functionality create a new test for IncomeCalulator. In my example I did also create a new source folder "test" before in which I place the test classes.
import income.exceptions.CalcMethodException;
import income.exceptions.PositionException;
import income.method.ICalcMethod;
import org.easymock.EasyMock;
import org.junit.Before;
import org.junit.Test;
@Before
calcMethod = EasyMock.createMock(ICalcMethod.class);
@Test
EasyMock.expect(calcMethod.calc(Position.BOSS)).andReturn(70000.0).times(2);
EasyMock.expect(calcMethod.calc(Position.PROGRAMMER)).andReturn(50000.0);
EasyMock.replay(calcMethod);
calc.setCalcMethod(calcMethod);
try {
calc.calc();
} catch (PositionException e) {}
calc.setPosition(Position.BOSS);
assertEquals(70000.0, calc.calc());
assertEquals(70000.0, calc.calc());
calc.setPosition(Position.PROGRAMMER);
assertEquals(50000.0, calc.calc());
calc.setPosition(Position.SURFER);
EasyMock.verify(calcMethod);
@Test(expected = CalcMethodException.class)
calc.setPosition(Position.SURFER);
calc.calc();
@Test(expected = PositionException.class)
EasyMock.expect(calcMethod.calc(Position.BOSS)).andReturn(70000.0);
EasyMock.replay(calcMethod);
calc.setCalcMethod(calcMethod);
calc.calc();
@Test(expected = PositionException.class)
EasyMock.expect(calcMethod.calc(Position.SURFER)).andThrow(
EasyMock.replay(calcMethod);
calc.setPosition(Position.SURFER);
calc.setCalcMethod(calcMethod);
calc.calc();
The expect method tells easy mock to expect a certain method with certain arguments. andReturn defines the return value of this method. The method times defines how often the Mock object will be called.
The reply method needs to be called to make the Mock object available.
After execution of the test you can call the method verify to check if the Mock Object was called as defined.
3. Thank you
Before posting questions, please see the vogella FAQ . If you have questions or find an error in this article please use the www.vogella.de Google Group . I have created a short list how to create good questions which might also help you.
5.1. Performance
Lars Vogel
Version 1.1
25.06.2011
Revision History Revision 0.1 created Revision 0.2 - 1.1 30.12.2008 - 25.06.2011 Lars Vogel 07.12.2007 Lars Vogel
This article gives an overview of the usage of regular expressions in general and describes the usage of regular expressions with Java. It also provides several Java regular expression examples.
Table of Contents
1. Regular Expressions 1.1. Overview 1.2. Usage 1.3. Junit 2. Regular Expressions 2.1. Common matching symbols 2.2. Metacharacters 2.3. Quantifier 3. Using Regular Expressions with String.matches()
3.1. Overview 3.2. Examples 4. Pattern and Matcher 5. Java Regex Examples 5.1. Or 5.2. Phone number 5.3. Check for a certain number range 5.4. Building a link checker 6. Thank you 7. Questions and Discussion 8. Links and Literature
1. Regular Expressions
1.1. Overview
A regular expression define a search pattern for strings. This pattern may match one or several times or not at all for a given string. The abbreviation for regular expression is "regex".
A simple example for a regular expression is a (literal) string. For example the regex "Hello World" will match exactly the phrase "Hello World". Another example for a regular expression is "." (dot) which matches any single character; it would match for example "a" or "z" or "1".
1.2. Usage
Regular expressions are used in several programming languages, e.g. Java but also Perl, Groovy, etc. Unfortunately each language / program supports regex slightly different.
The pattern defined by the regular expression is applied on the string from left to right. Once a source character has been used in a match, it cannot be reused. For example the regex "aba" will match "ababababa" only two times (aba_aba__).
1.3. Junit
Some of the following examples use JUnit to validate the result. You should be able to adjust them in case if you don't want to use JUnit. To learn about JUnit please see JUnit Tutorial .
2. Regular Expressions
The following is an overview of regular expressions. This chapter is supposed to be a references for the different regex elements.
Table 1.
Description
Matches any sign regex must match at the beginning of the line Finds regex must match at the end of the line Set definition, can match the letter a or b or c Set definition, can match a or b or c followed by either v or z When a "^" appears as the first character inside [] when it negates the pattern. This can match any character except a or b or c
[a-d1-7] X|Z XZ $
Ranges, letter between a and d and figures from 1 to 7, will not match d1 Finds X or Z Finds X directly followed by Z Checks if a line end follows
2.2. Metacharacters
The following metacharacters have a pre-defined meaning and make certain common pattern easier to use, e.g. d instead of [0..9].
Table 2.
Regular Expression \d \D \s \S
Description Any digit, short for [0-9] A non-digit, short for [^0-9] A whitespace character, short for [ \t\n\x0b\r\f] A non-whitespace character, for short for [^\s]
Description A word character, short for [a-zA-Z_0-9] A non-word character [^\w] Several non-whitespace characters
2.3. Quantifier
A quantifier defines how often an element can occur. The symbols ?, *, + and {} define the quantity of the regular expressions
Table 3.
Regular Expression *
Description
Examples
+ ? {X}
Occurs one or more times, is short for {1,} Occurs no or one times, ? is short for {0,1} Occurs X number of times, {} describes the order of the preceding liberal
X+ - Finds one or several letter X X? -Finds no or exactly one letter X \d{3} - Three digits, .{10} - any character sequence of length 10 \d{1,4}- \d must occur at least once and at a maximum of four
{X,Y}
*?
? after a qualifier makes it a "reluctant quantifier", it tries to find the smallest match.
3.1. Overview
Strings in Java have build in support for regular expressions. Stings have three build in methods for regular expressions. These methods do not compile the pattern and are therefore slower then using a pattern and a matcher as described later in this article.
The backslash is an escape character in Java Strings. e.g. backslash has a predefine meaning in Java. You have to use "" to define a single backslash. If you want to define "w" then you must be using "w" in your regex. If you want to use backslash you as a literal you have to type as is also a escape charactor in regular expressions.
Table 4.
Description Evaluates if "regex" matches s. Returns only true if the WHOLE string can be matched Creates array with substrings of s divided at occurance of "regex". "regex" is not included in the result.
s.replace("regex"), "replacement"
Create for the following example the Java project "de.vogella.regex.test". package de.vogella.regex.test;
public static final String EXAMPLE_TEST = "This is my small example string which I'm going to use for pattern matching.";
System.out.println(EXAMPLE_TEST.matches("w.*"));
System.out.println(splitString.length);// Should be 14
System.out.println(string);
System.out.println(EXAMPLE_TEST.replaceAll("s+", "t"));
3.2. Examples
The following class gives several examples for the usage of regular expressions with strings. See the comment for the purpose. package de.vogella.regex.string;
return s.matches("true");
return s.matches("[tT]rue");
// or "yes" or "Yes"
return s.matches("[tT]rue|[yY]es");
return s.matches(".*true.*");
return s.matches("[a-zA-Z]{3}");
//
return s.matches("[a-Z][a-Z][a-Z]");
// Returns true if the string does not have a number at the beginning
return s.matches("^[^d].*");
return s.matches("([w&&[^b]])*");
return s.matches("[^0-9]*[12]?[0-9]{1,2}[^0-9]*");
import org.junit.Before;
import org.junit.Test;
private StringMatcher m;
@Before
m = new StringMatcher();
@Test
assertTrue(m.isTrue("true"));
assertFalse(m.isTrue("true2"));
assertFalse(m.isTrue("True"));
@Test
assertTrue(m.isTrueVersion2("true"));
assertFalse(m.isTrueVersion2("true2"));
assertTrue(m.isTrueVersion2("True"));;
@Test
assertTrue(m.isTrueOrYes("true"));
assertTrue(m.isTrueOrYes("yes"));
assertTrue(m.isTrueOrYes("Yes"));
assertFalse(m.isTrueOrYes("no"));
@Test
assertTrue(m.containsTrue("thetruewithin"));
@Test
assertTrue(m.isThreeLetters("abc"));
assertFalse(m.isThreeLetters("abcd"));
@Test
assertTrue(m.isNoNumberAtBeginning("abc"));
assertFalse(m.isNoNumberAtBeginning("1abcd"));
assertTrue(m.isNoNumberAtBeginning("a1bcd"));
assertTrue(m.isNoNumberAtBeginning("asdfdsf"));
@Test
assertTrue(m.isIntersection("1"));
assertFalse(m.isIntersection("abcksdfkdskfsdfdsf"));
assertTrue(m.isIntersection("skdskfjsmcnxmvjwque484242"));
@Test
assertTrue(m.isLessThenThreeHundret("288"));
assertFalse(m.isLessThenThreeHundret("3288"));
assertFalse(m.isLessThenThreeHundret("328 8"));
assertTrue(m.isLessThenThreeHundret("1"));
assertTrue(m.isLessThenThreeHundret("99"));
assertFalse(m.isLessThenThreeHundret("300"));
For advanced regular expressions the classes you java.util.regex.Pattern and java.util.regex.Matcher are used.
You first create a Pattern object which defines the regular expression. This pattern object allows create a Matcher object for a given string. This matcher object then allows you to do regex operations on the string. package de.vogella.regex.test;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public static final String EXAMPLE_TEST = "This is my small example string which I'm going to use for pattern matching.";
// In case you would like to ignore case sensitivity you could use this
// statement
while (matcher.find()) {
System.out.println(matcher.group());
// Now create a new pattern and matcher to replace whitespace with tabs
System.out.println(matcher2.replaceAll("t"));
5.1. Or
Task: Write a regular expression which matches a text line if this text line contains either the word "Joe" or the word "Jim" or both. Create a project "de.vogella.regex.eitheror" and the following class. package de.vogella.regex.eitheror;
import org.junit.Test;
@Test
assertTrue(s.matches(".*(jim|joe).*"));
s = "humbapumpa jom";
assertFalse(s.matches(".*(jim|joe).*"));
s = "humbaPumpa joe";
assertTrue(s.matches(".*(jim|joe).*"));
assertTrue(s.matches(".*(jim|joe).*"));
Task: Write a regular expression which matches any phone number. A phone number in this example consists either out of 7 numbers in a row or out of 3 number a (white)space or a dash and then 4 numbers. package de.vogella.regex.phonenumber;
import org.junit.Test;
@Test
String s= "1233323322";
assertFalse(s.matches(pattern));
s = "1233323";
assertTrue(s.matches(pattern));
s = "123 3323";
assertTrue(s.matches(pattern));
The following example will check if a text contains a number with 3 digits.
Create the Java project "de.vogella.regex.numbermatch" and the following class. package de.vogella.regex.numbermatch;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.junit.Test;
@Test
String s= "1233";
assertTrue(test(s));
s= "0";
assertFalse(test(s));
assertTrue(test(s));
s = "99900234";
assertTrue(test(s));
if (matcher.find()){
return true;
return false;
The following exampleallows to extract all valid links from a webpage. It does not consider links with start with "javascript:" or "mailto:".
Create the Java project "de.vogella.regex.weblinks" and the following class package de.vogella.regex.weblinks;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
this.root = root;
htmltag = Pattern.compile("<ab[^>]*href="[^>]*>(.*?)</a>");
link = Pattern.compile("href="[^>]*">");
try {
String s;
builder.append(s);
while (tagmatch.find()) {
matcher.find();
.replaceFirst("">", "");
if (valid(link)) {
links.add(makeAbsolute(url, link));
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
return links;
if (s.matches("javascript:.*|mailto:.*")) {
return false;
return true;
if (link.matches("http://.*")) {
return link;
throw new RuntimeException("Cannot make the link absolute. Url: " + url
JAXB Tutorial
Lars Vogel
Version 1.3
08.03.2011
Revision History Revision 0.1 created Revision 0.2 - 1.3 bug fixes and enhancements 21.10.2008 - 08.03.2011 Lars Vogel 26.02.2008 Lars Vogel
JAXB Tutorial
This tutorial give an introduction to Java Architecture for XML Binding (JAXB). This tutorial is based on Java 6.0.
Table of Contents
1. Overview 2. JAXB 2 - Java Architecture for XML Binding 2.1. Overview 2.2. Usage 3. Thank you 4. Questions and Discussion 5. Links and Literature 5.1. Source Code 5.2. Links and Literature 5.3. vogella Resources
1. Overview
Java Architecture for XML Binding (JAXB) is a Java standard that defines how Java objects are converted to/from XML (specified using a standard set of mappings. JAXB defines a programmer API for reading and writing Java objects to / from XML documents and a service provider which / from from XML documents allows the selection of the JAXB implementation JAXB applies a lot of defaults thus making reading and writing of XML via Java very easy.
The following will explain the JAXB interface, for an introduction into using XML with Java please see Java XML tutorial .
2.1. Overview
Table 1.
Allows to define the order in which the fields are written in the XML file
Define the XML element which will be used. Only need to be used if the neuNeu is different then the JavaBeans Name
2.2. Usage
Create the following domain model with the JAXB annotations. package de.vogella.xml.jaxb.model;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
@XmlRootElement(name = "book")
// If you want you can define the order in which the fields are written
// Optional
// If you like the variable name, e.g. "name", you can easily change this
@XmlElement(name = "bookName")
return name;
this.name = name;
return author;
this.author = author;
return publisher;
this.publisher = publisher;
return isbn;
this.isbn = isbn;
package de.vogella.xml.jaxb.model;
import java.util.ArrayList;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;
//This statement means that class "Bookstore.java" is the root-element of our example
@XmlRootElement(namespace = "de.vogella.xml.jaxb.model")
@XmlElementWrapper(name = "bookList")
@XmlElement(name = "book")
this.bookList = bookList;
return bookList;
return name;
this.name = name;
return location;
this.location = location;
Create the following test program for writing and reading the XML file. package test;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.ArrayList;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import de.vogella.xml.jaxb.model.Book;
import de.vogella.xml.jaxb.model.Bookstore;
// create books
book1.setIsbn("978-0060554736");
book1.setName("The Game");
book1.setAuthor("Neil Strauss");
book1.setPublisher("Harpercollins");
bookList.add(book1);
book2.setIsbn("978-3832180577");
book2.setName("Feuchtgebiete");
book2.setAuthor("Charlotte Roche");
book2.setPublisher("Dumont Buchverlag");
bookList.add(book2);
bookstore.setName("Fraport Bookstore");
bookstore.setLocation("Frankfurt Airport");
bookstore.setBookList(bookList);
Marshaller m = context.createMarshaller();
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
m.marshal(bookstore, System.out);
Writer w = null;
try {
w = new FileWriter(BOOKSTORE_XML);
m.marshal(bookstore, w);
} finally {
try {
w.close();
} catch (Exception e) {
System.out.println();
Unmarshaller um = context.createUnmarshaller();
BOOKSTORE_XML));
+ bookstore2.getBooksList().get(i).getAuthor());
If you run the BookMain a XML file will be created from the object. Afterwards the file is read again and the object are created again.