Μεθοδολογίες Προγραμματισμού ΙΙ Έλεγχος Λογισμικού - ECLIPSE JUNIT – TDD TFD + Refactoring
JUnit Eclipse Tutorial
Transcript of JUnit Eclipse Tutorial
-
8/3/2019 JUnit Eclipse Tutorial
1/46
JUnit Tutorial
Lars Vogel
Version 1.4
Copyright 2007 - 2011 Lars Vogel
21.08.2011
Revision History
Revision 0.1-0.5 03.09.2007 Lars Vogel
JUnit description
Revision 0.6 - 1.4 10.05.2008 - 21.08.2011 Lars 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
http://www.vogella.de/articles/JUnit/article.html#unittestinghttp://www.vogella.de/articles/JUnit/article.html#unittestinghttp://www.vogella.de/articles/JUnit/article.html#junit_introhttp://www.vogella.de/articles/JUnit/article.html#junit_introhttp://www.vogella.de/articles/JUnit/article.html#unittesting_junithttp://www.vogella.de/articles/JUnit/article.html#unittesting_junithttp://www.vogella.de/articles/JUnit/article.html#junit_installationhttp://www.vogella.de/articles/JUnit/article.html#junit_installationhttp://www.vogella.de/articles/JUnit/article.html#juniteclipsehttp://www.vogella.de/articles/JUnit/article.html#juniteclipsehttp://www.vogella.de/articles/JUnit/article.html#juniteclipse_prephttp://www.vogella.de/articles/JUnit/article.html#juniteclipse_prephttp://www.vogella.de/articles/JUnit/article.html#juniteclipse_classhttp://www.vogella.de/articles/JUnit/article.html#juniteclipse_classhttp://www.vogella.de/articles/JUnit/article.html#juniteclipse_testhttp://www.vogella.de/articles/JUnit/article.html#juniteclipse_testhttp://www.vogella.de/articles/JUnit/article.html#juniteclipse_eclipsehttp://www.vogella.de/articles/JUnit/article.html#juniteclipse_eclipsehttp://www.vogella.de/articles/JUnit/article.html#juniteclipse_codehttp://www.vogella.de/articles/JUnit/article.html#juniteclipse_codehttp://www.vogella.de/articles/JUnit/article.html#usingjunithttp://www.vogella.de/articles/JUnit/article.html#usingjunithttp://www.vogella.de/articles/JUnit/article.html#usingjunit_staticimportshttp://www.vogella.de/articles/JUnit/article.html#usingjunit_staticimportshttp://www.vogella.de/articles/JUnit/article.html#usingjunit_staticimportshttp://www.vogella.de/articles/JUnit/article.html#usingjunithttp://www.vogella.de/articles/JUnit/article.html#juniteclipse_codehttp://www.vogella.de/articles/JUnit/article.html#juniteclipse_eclipsehttp://www.vogella.de/articles/JUnit/article.html#juniteclipse_testhttp://www.vogella.de/articles/JUnit/article.html#juniteclipse_classhttp://www.vogella.de/articles/JUnit/article.html#juniteclipse_prephttp://www.vogella.de/articles/JUnit/article.html#juniteclipsehttp://www.vogella.de/articles/JUnit/article.html#junit_installationhttp://www.vogella.de/articles/JUnit/article.html#unittesting_junithttp://www.vogella.de/articles/JUnit/article.html#junit_introhttp://www.vogella.de/articles/JUnit/article.html#unittesting -
8/3/2019 JUnit Eclipse Tutorial
2/46
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 seeEasyMock Tutorial
1.2. Unit Testing with JUnit
JUnit 4.x is a test framework which uses annotation to identify the methods which contain tests.JUnitassumes 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 likeEclipse or the class "org.junit.runner.JUnitCore" to run the test.
1.3. Installation of JUnit
Download JUnit4.x.jar from theJUnit 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. SeeEclipse IDE Tutorialto learn how to do this in Eclipse.
2. JUnit with Eclipse
2.1. Preparation
http://www.vogella.de/articles/JUnit/article.html#usingjunit_annotationshttp://www.vogella.de/articles/JUnit/article.html#usingjunit_annotationshttp://www.vogella.de/articles/JUnit/article.html#usingjunit_assertshttp://www.vogella.de/articles/JUnit/article.html#usingjunit_assertshttp://www.vogella.de/articles/JUnit/article.html#thankyouhttp://www.vogella.de/articles/JUnit/article.html#thankyouhttp://www.vogella.de/articles/JUnit/article.html#questionshttp://www.vogella.de/articles/JUnit/article.html#questionshttp://www.vogella.de/articles/JUnit/article.html#resourceshttp://www.vogella.de/articles/JUnit/article.html#resourceshttp://www.vogella.de/articles/JUnit/article.html#junit_linkshttp://www.vogella.de/articles/JUnit/article.html#junit_linkshttp://www.vogella.de/articles/JUnit/article.html#resources_generalhttp://www.vogella.de/articles/JUnit/article.html#resources_generalhttp://www.vogella.de/articles/EasyMock/article.htmlhttp://www.vogella.de/articles/EasyMock/article.htmlhttp://www.vogella.de/articles/EasyMock/article.htmlhttp://www.vogella.de/articles/JUnit/article.htmlhttp://www.vogella.de/articles/JUnit/article.htmlhttp://www.vogella.de/articles/JUnit/article.htmlhttp://www.vogella.de/articles/Eclipse/article.htmlhttp://www.vogella.de/articles/Eclipse/article.htmlhttp://www.vogella.de/articles/Eclipse/article.htmlhttp://www.junit.org/http://www.junit.org/http://www.junit.org/http://www.vogella.de/articles/Eclipse/article.htmlhttp://www.vogella.de/articles/Eclipse/article.htmlhttp://www.vogella.de/articles/Eclipse/article.htmlhttp://www.vogella.de/articles/Eclipse/article.htmlhttp://www.junit.org/http://www.vogella.de/articles/Eclipse/article.htmlhttp://www.vogella.de/articles/JUnit/article.htmlhttp://www.vogella.de/articles/EasyMock/article.htmlhttp://www.vogella.de/articles/JUnit/article.html#resources_generalhttp://www.vogella.de/articles/JUnit/article.html#junit_linkshttp://www.vogella.de/articles/JUnit/article.html#resourceshttp://www.vogella.de/articles/JUnit/article.html#questionshttp://www.vogella.de/articles/JUnit/article.html#thankyouhttp://www.vogella.de/articles/JUnit/article.html#usingjunit_assertshttp://www.vogella.de/articles/JUnit/article.html#usingjunit_annotations -
8/3/2019 JUnit Eclipse Tutorial
3/46
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.
2.2. Create a Java class
-
8/3/2019 JUnit Eclipse Tutorial
4/46
Create a package "de.vogella.junit.first" and the following class.
package de.vogella.junit.first;
public class MyClass {
public int multiply(int x, int y) {
return x / y;
}
}
2.3. Create a JUnit test
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.
-
8/3/2019 JUnit Eclipse Tutorial
5/46
Press next and select the methods which you want to test.
-
8/3/2019 JUnit Eclipse Tutorial
6/46
If you have not yet JUnit in your classpath, Eclipse will asked you if it should be added to the classpath.
Create a test with the following code.
-
8/3/2019 JUnit Eclipse Tutorial
7/46
package de.vogella.junit.first;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class MyClassTest {
@Test
public void testMultiply() {
MyClass tester = new MyClass();
assertEquals("Result", 50, tester.multiply(10, 5));
}
}
2.4. Run your test via Eclipse
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.
-
8/3/2019 JUnit Eclipse Tutorial
8/46
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. SeeBug 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 })
publicclass AllTests {
}
https://bugs.eclipse.org/bugs/show_bug.cgi?id=155828https://bugs.eclipse.org/bugs/show_bug.cgi?id=155828https://bugs.eclipse.org/bugs/show_bug.cgi?id=155828https://bugs.eclipse.org/bugs/show_bug.cgi?id=155828 -
8/3/2019 JUnit Eclipse Tutorial
9/46
2.5. Run your test via code
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;
publicclass MyTestRunner {
publicstaticvoid main(String[] args) {
Result result = JUnitCore.runClasses(MyClassTest.class);
for (Failure failure : result.getFailures()) {
System.out.println(failure.toString());
}
}
}
3. JUnit (more) in Detail
3.1. Static imports with Eclipse
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.
-
8/3/2019 JUnit Eclipse Tutorial
10/46
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.
I suggest to add at least the following new members.
org.junit.Assert.assertTrue
org.junit.Assert.assertFalse
org.junit.Assert.assertEquals
org.junit.Assert.fail
3.2. Annotations
The following give an overview of the available annotations in JUnit 4.x
Table 1. Annotations
Annotation Description@Test public void method() Annotation @Test identifies that this method is a test method.
@Before public void method() Will perform the method() before each test. This method can prepare the test
environment, e.g. read input data, initialize the class)
@After public void method() Test method must start with test
@BeforeClass public void method() 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
@AfterClass public void method() Will perform the method after all tests have finished. This can be used to perform
-
8/3/2019 JUnit Eclipse Tutorial
11/46
Annotation Descriptionclean-up activities for example be used to disconnect to a database
@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
3.3. Assert statements
The following gives an overview of the available test methods:
Table 2. Test methods
Statement Descriptionfail(String) 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,
tolerance)
Usage for float and double; the tolerance are the number of decimals which
must be the same
assertNull([message], object) Checks if the object is null
assertNotNull([message], object) Check if the object is not null
assertSame([String], expected, actual) Check if both variables refer to the same object
assertNotSame([String], expected, actual) Check that both variables refer not to the same object
assertTrue([message], boolean condition) Check if the boolean condition is true.
4. Thank you
Please help me to support this article:
5. Questions and Discussion
-
8/3/2019 JUnit Eclipse Tutorial
12/46
Before posting questions, please see thevogella FAQ . If you have questions or find an error in this article please use
thewww.vogella.de Google Group . I have created a short listhow to create good questionswhich might also help you.
6. Links and Literature
6.1. JUnit Resources
http://www.junit.org/JUnit Homepage
6.2. vogella Resources
Eclipse RCP Training (German) Eclipse RCP Training with Lars Vogel
Android Tutorial Introduction to Android Programming
GWT Tutorial Program in Java and compile to JavaScript and HTML
Eclipse RCP Tutorial Create native applications in Java
JUnit Tutorial Test your application
Git Tutorial Put everything you have under distributed version control system
Testing with EasyMock - Tutorial
Lars Vogel
Version 0.4
Copyright 2011 Lars Vogel
14.06.2011
Revision History
Revision 0.1 06.02.2010 Lars Vogel
created
Revision 0.2 - 0.4 06.02.2010 - 14.06.2011 Lars Vogel
bug fixed and enhancements
http://www.vogella.de/faq.htmlhttp://www.vogella.de/faq.htmlhttp://www.vogella.de/faq.htmlhttp://groups.google.com/group/vogellahttp://groups.google.com/group/vogellahttp://groups.google.com/group/vogellahttp://www.vogella.de/blog/2010/03/09/asking-community-questions/http://www.vogella.de/blog/2010/03/09/asking-community-questions/http://www.junit.org/http://www.junit.org/http://www.vogella.de/training/eclipsercp.htmlhttp://www.vogella.de/training/eclipsercp.htmlhttp://www.vogella.de/articles/Android/article.htmlhttp://www.vogella.de/articles/Android/article.htmlhttp://www.vogella.de/articles/GWT/article.htmlhttp://www.vogella.de/articles/GWT/article.htmlhttp://www.vogella.de/articles/EclipseRCP/article.htmlhttp://www.vogella.de/articles/EclipseRCP/article.htmlhttp://www.vogella.de/articles/JUnit/article.htmlhttp://www.vogella.de/articles/Git/article.htmlhttp://www.vogella.de/articles/Git/article.htmlhttp://www.vogella.de/articles/Git/article.htmlhttp://www.vogella.de/articles/JUnit/article.htmlhttp://www.vogella.de/articles/EclipseRCP/article.htmlhttp://www.vogella.de/articles/GWT/article.htmlhttp://www.vogella.de/articles/Android/article.htmlhttp://www.vogella.de/training/eclipsercp.htmlhttp://www.junit.org/http://www.vogella.de/blog/2010/03/09/asking-community-questions/http://groups.google.com/group/vogellahttp://www.vogella.de/faq.html -
8/3/2019 JUnit Eclipse Tutorial
13/46
Testing with EasyMock
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
1. EasyMock and Mock Objects Overview
The following is based on an understandingJUnit. In case your are not familiar with JUnit please check the
followingJUnit Tutorial .
1.1. Testing and Mock Objects
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
http://www.vogella.de/articles/EasyMock/article.html#introductionhttp://www.vogella.de/articles/EasyMock/article.html#introductionhttp://www.vogella.de/articles/EasyMock/article.html#introduction_mockobjectshttp://www.vogella.de/articles/EasyMock/article.html#introduction_mockobjectshttp://www.vogella.de/articles/EasyMock/article.html#introduction_easymocktesthttp://www.vogella.de/articles/EasyMock/article.html#introduction_easymocktesthttp://www.vogella.de/articles/EasyMock/article.html#easymocktesthttp://www.vogella.de/articles/EasyMock/article.html#easymocktesthttp://www.vogella.de/articles/EasyMock/article.html#thankyouhttp://www.vogella.de/articles/EasyMock/article.html#thankyouhttp://www.vogella.de/articles/EasyMock/article.html#questionshttp://www.vogella.de/articles/EasyMock/article.html#questionshttp://www.vogella.de/articles/EasyMock/article.html#resourceshttp://www.vogella.de/articles/EasyMock/article.html#resourceshttp://www.vogella.de/articles/EasyMock/article.html#resources_performancehttp://www.vogella.de/articles/EasyMock/article.html#resources_performancehttp://www.vogella.de/articles/JUnit/article.htmlhttp://www.vogella.de/articles/JUnit/article.htmlhttp://www.vogella.de/articles/JUnit/article.htmlhttp://www.vogella.de/articles/JUnit/article.htmlhttp://www.vogella.de/articles/JUnit/article.htmlhttp://www.vogella.de/articles/JUnit/article.htmlhttp://www.vogella.de/articles/JUnit/article.htmlhttp://www.vogella.de/articles/JUnit/article.htmlhttp://www.vogella.de/articles/EasyMock/article.html#resources_performancehttp://www.vogella.de/articles/EasyMock/article.html#resourceshttp://www.vogella.de/articles/EasyMock/article.html#questionshttp://www.vogella.de/articles/EasyMock/article.html#thankyouhttp://www.vogella.de/articles/EasyMock/article.html#easymocktesthttp://www.vogella.de/articles/EasyMock/article.html#introduction_easymocktesthttp://www.vogella.de/articles/EasyMock/article.html#introduction_mockobjectshttp://www.vogella.de/articles/EasyMock/article.html#introduction -
8/3/2019 JUnit Eclipse Tutorial
14/46
EasyMock is a popular mock framework which can be easily used in conjunction withJUnit. The following demonstrates
the usage of EasyMock.
2. Using Easy Mock and Junit
DownloadEasyMock from theEasyMock Homepage and add the easymock.jar to your classpath. You also need to
downloadObjenesis andCgliband 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;
public enum Position {
BOSS, PROGRAMMER, SURFER
}
package income.exceptions;
publicclass PositionException extends RuntimeException {
privatestaticfinallong serialVersionUID = 1L;
public PositionException(String message) {
super(message);
}
}
package income.exceptions;
publicclass CalcMethodException extends RuntimeException {
privatestaticfinallong serialVersionUID = 1L;
public CalcMethodException(String message) {
http://www.vogella.de/articles/JUnit/article.htmlhttp://www.vogella.de/articles/JUnit/article.htmlhttp://www.vogella.de/articles/JUnit/article.htmlhttp://easymock.org/http://easymock.org/http://easymock.org/http://easymock.org/http://easymock.org/http://easymock.org/http://objenesis.googlecode.com/svn/docs/download.htmlhttp://objenesis.googlecode.com/svn/docs/download.htmlhttp://objenesis.googlecode.com/svn/docs/download.htmlhttp://cglib.sourceforge.net/http://cglib.sourceforge.net/http://cglib.sourceforge.net/http://cglib.sourceforge.net/http://objenesis.googlecode.com/svn/docs/download.htmlhttp://easymock.org/http://easymock.org/http://www.vogella.de/articles/JUnit/article.html -
8/3/2019 JUnit Eclipse Tutorial
15/46
super(message);
}
}
package income.method;
import income.Position;
publicinterface ICalcMethod {
publicabstractdouble calc(Position position);
}
package income;
import income.exceptions.CalcMethodException;
import income.exceptions.PositionException;
import income.method.ICalcMethod;
publicclass IncomeCalculator{
private ICalcMethod calcMethod;
private Position position;
publicvoid setCalcMethod(ICalcMethod calcMethod){
this.calcMethod = calcMethod;
}
publicvoid setPosition(Position position){
this.position = position;
}
publicdouble calc (){
-
8/3/2019 JUnit Eclipse Tutorial
16/46
if (calcMethod==null){
thrownew CalcMethodException("CalcMethod not yet maintained");
}
if (position==null){
thrownew PositionException("Position not yet maintained");
}
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.
Here is the test using EasyMock.
package income;
importstatic org.junit.Assert.assertEquals;
importstatic org.junit.Assert.fail;
import income.exceptions.CalcMethodException;
import income.exceptions.PositionException;
import income.method.ICalcMethod;
import org.easymock.EasyMock;
import org.junit.Before;
import org.junit.Test;
-
8/3/2019 JUnit Eclipse Tutorial
17/46
-
8/3/2019 JUnit Eclipse Tutorial
18/46
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)
publicvoid testNoCalc() {
calc.setPosition(Position.SURFER);
calc.calc();
}
@Test(expected = PositionException.class)
publicvoid testNoPosition() {
EasyMock.expect(calcMethod.calc(Position.BOSS)).andReturn(70000.0);
EasyMock.replay(calcMethod);
calc.setCalcMethod(calcMethod);
calc.calc();
}
-
8/3/2019 JUnit Eclipse Tutorial
19/46
@Test(expected = PositionException.class)
publicvoid testCalc2() {
// Setting up the expected value of the method call calc
EasyMock.expect(calcMethod.calc(Position.SURFER)).andThrow(
new PositionException("Don't know this guy")).times(1);
// Setup is finished need to activate the mock
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
Please help me to support this article:
. Questions and Discussion
Before posting questions, please see thevogella FAQ . If you have questions or find an error in this article please use
thewww.vogella.de Google Group . I have created a short listhow to create good questionswhich might also help you.
5. Links and Literature
http://www.vogella.de/faq.htmlhttp://www.vogella.de/faq.htmlhttp://www.vogella.de/faq.htmlhttp://groups.google.com/group/vogellahttp://groups.google.com/group/vogellahttp://groups.google.com/group/vogellahttp://www.vogella.de/blog/2010/03/09/asking-community-questions/http://www.vogella.de/blog/2010/03/09/asking-community-questions/http://www.vogella.de/blog/2010/03/09/asking-community-questions/http://groups.google.com/group/vogellahttp://www.vogella.de/faq.html -
8/3/2019 JUnit Eclipse Tutorial
20/46
5.1. Performance
https://www.ibm.com/developerworks/java/library/j-jtp09196/Java theory and practice: Instrumenting applications with
JMX
Java Regex Tutorial
Lars Vogel
Version 1.1
Copyright 2007 - 2011 Lars Vogel
25.06.2011
Revision History
Revision 0.1 07.12.2007 Lars Vogel
created
Revision 0.2 - 1.1 30.12.2008 - 25.06.2011 Lars Vogel
Java and Regular Expressions
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()
https://www.ibm.com/developerworks/java/library/j-jtp09196/https://www.ibm.com/developerworks/java/library/j-jtp09196/http://www.vogella.de/articles/JavaRegularExpressions/article.html#introductionhttp://www.vogella.de/articles/JavaRegularExpressions/article.html#introductionhttp://www.vogella.de/articles/JavaRegularExpressions/article.html#introduction_regexhttp://www.vogella.de/articles/JavaRegularExpressions/article.html#introduction_regexhttp://www.vogella.de/articles/JavaRegularExpressions/article.html#introduction_usagehttp://www.vogella.de/articles/JavaRegularExpressions/article.html#introduction_usagehttp://www.vogella.de/articles/JavaRegularExpressions/article.html#introduction_junithttp://www.vogella.de/articles/JavaRegularExpressions/article.html#introduction_junithttp://www.vogella.de/articles/JavaRegularExpressions/article.html#regexhttp://www.vogella.de/articles/JavaRegularExpressions/article.html#regexhttp://www.vogella.de/articles/JavaRegularExpressions/article.html#regex_starterhttp://www.vogella.de/articles/JavaRegularExpressions/article.html#regex_starterhttp://www.vogella.de/articles/JavaRegularExpressions/article.html#regex_metacharactershttp://www.vogella.de/articles/JavaRegularExpressions/article.html#regex_metacharactershttp://www.vogella.de/articles/JavaRegularExpressions/article.html#regex_quantifierhttp://www.vogella.de/articles/JavaRegularExpressions/article.html#regex_quantifierhttp://www.vogella.de/articles/JavaRegularExpressions/article.html#stringhttp://www.vogella.de/articles/JavaRegularExpressions/article.html#stringhttp://www.vogella.de/articles/JavaRegularExpressions/article.html#stringhttp://www.vogella.de/articles/JavaRegularExpressions/article.html#regex_quantifierhttp://www.vogella.de/articles/JavaRegularExpressions/article.html#regex_metacharactershttp://www.vogella.de/articles/JavaRegularExpressions/article.html#regex_starterhttp://www.vogella.de/articles/JavaRegularExpressions/article.html#regexhttp://www.vogella.de/articles/JavaRegularExpressions/article.html#introduction_junithttp://www.vogella.de/articles/JavaRegularExpressions/article.html#introduction_usagehttp://www.vogella.de/articles/JavaRegularExpressions/article.html#introduction_regexhttp://www.vogella.de/articles/JavaRegularExpressions/article.html#introductionhttps://www.ibm.com/developerworks/java/library/j-jtp09196/ -
8/3/2019 JUnit Eclipse Tutorial
21/46
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 can be used to search, edit and manipulate text.
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 seeJUnit Tutorial
.
http://www.vogella.de/articles/JavaRegularExpressions/article.html#string_overviewhttp://www.vogella.de/articles/JavaRegularExpressions/article.html#string_overviewhttp://www.vogella.de/articles/JavaRegularExpressions/article.html#string_exampleshttp://www.vogella.de/articles/JavaRegularExpressions/article.html#string_exampleshttp://www.vogella.de/articles/JavaRegularExpressions/article.html#regexjavahttp://www.vogella.de/articles/JavaRegularExpressions/article.html#regexjavahttp://www.vogella.de/articles/JavaRegularExpressions/article.html#exampleshttp://www.vogella.de/articles/JavaRegularExpressions/article.html#exampleshttp://www.vogella.de/articles/JavaRegularExpressions/article.html#examples_orhttp://www.vogella.de/articles/JavaRegularExpressions/article.html#examples_orhttp://www.vogella.de/articles/JavaRegularExpressions/article.html#examples_phonehttp://www.vogella.de/articles/JavaRegularExpressions/article.html#examples_phonehttp://www.vogella.de/articles/JavaRegularExpressions/article.html#examples_numberhttp://www.vogella.de/articles/JavaRegularExpressions/article.html#examples_numberhttp://www.vogella.de/articles/JavaRegularExpressions/article.html#examples_linkcheckerhttp://www.vogella.de/articles/JavaRegularExpressions/article.html#examples_linkcheckerhttp://www.vogella.de/articles/JavaRegularExpressions/article.html#thankyouhttp://www.vogella.de/articles/JavaRegularExpressions/article.html#thankyouhttp://www.vogella.de/articles/JavaRegularExpressions/article.html#questionshttp://www.vogella.de/articles/JavaRegularExpressions/article.html#questionshttp://www.vogella.de/articles/JavaRegularExpressions/article.html#resourceshttp://www.vogella.de/articles/JavaRegularExpressions/article.html#resourceshttp://www.vogella.de/articles/JUnit/article.htmlhttp://www.vogella.de/articles/JUnit/article.htmlhttp://www.vogella.de/articles/JUnit/article.htmlhttp://www.vogella.de/articles/JUnit/article.htmlhttp://www.vogella.de/articles/JavaRegularExpressions/article.html#resourceshttp://www.vogella.de/articles/JavaRegularExpressions/article.html#questionshttp://www.vogella.de/articles/JavaRegularExpressions/article.html#thankyouhttp://www.vogella.de/articles/JavaRegularExpressions/article.html#examples_linkcheckerhttp://www.vogella.de/articles/JavaRegularExpressions/article.html#examples_numberhttp://www.vogella.de/articles/JavaRegularExpressions/article.html#examples_phonehttp://www.vogella.de/articles/JavaRegularExpressions/article.html#examples_orhttp://www.vogella.de/articles/JavaRegularExpressions/article.html#exampleshttp://www.vogella.de/articles/JavaRegularExpressions/article.html#regexjavahttp://www.vogella.de/articles/JavaRegularExpressions/article.html#string_exampleshttp://www.vogella.de/articles/JavaRegularExpressions/article.html#string_overview -
8/3/2019 JUnit Eclipse Tutorial
22/46
-
8/3/2019 JUnit Eclipse Tutorial
23/46
Regular Expression Description\w A word character, short for [a-zA-Z_0-9]
\W A non-word character [^\w]
\S+ 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.
RegularExpression
Description Examples
* Occurs zero or more times, is short for {0,} X* - Finds no or several letter X, .* - any
character sequence
+ Occurs one or more times, is short for {1,} X+ - Finds one or several letter X
? Occurs no or one times, ? is short for {0,1} X? -Finds no or exactly one letter X
{X} Occurs X number of times, {} describes the order of the
preceding liberal
\d{3} - Three digits, .{10} - any character
sequence of length 10
{X,Y} .Occurs between X and Y times, \d{1,4}- \d must occur at least once and at a
maximum of four
*? ? after a qualifier makes it a "reluctant quantifier", it tries to
find the smallest match.
3. Using Regular Expressions with String.matches()
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.
-
8/3/2019 JUnit Eclipse Tutorial
24/46
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.
Method Descriptions.matches("regex") Evaluates if "regex" matches s. Returns only true if the WHOLE string can be matched
s.split("regex") Creates array with substrings of s divided at occurance of "regex". "regex" is not included in the
result.
s.replace("regex"),
"replacement"
Replaces "regex" with "replacement
Create for the following example the Java project "de.vogella.regex.test".
package de.vogella.regex.test;
publicclass RegexTestStrings {
publicstaticfinal String EXAMPLE_TEST = "This is my small example string which
I'm going to use for pattern matching.";
publicstaticvoid main(String[] args) {
System.out.println(EXAMPLE_TEST.matches( "w.*"));
String[] splitString = (EXAMPLE_TEST.split("s+"));
System.out.println(splitString.length); // Should be 14
for (String string : splitString) {
System.out.println(string);
}
// Replace all whitespace with tabs
System.out.println(EXAMPLE_TEST.replaceAll( "s+", "t"));
-
8/3/2019 JUnit Eclipse Tutorial
25/46
}
}
3.2. Examples
Create for the following example the Java project "de.vogella.regex.string".
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;
publicclass StringMatcher {
// Returns true if the string matches exactly "true"
publicboolean isTrue(String s){
return s.matches("true");
}
// Returns true if the string matches exactly "true" or "True"
publicboolean isTrueVersion2(String s){
return s.matches("[tT]rue");
}
// Returns true if the string matches exactly "true" or "True"
// or "yes" or "Yes"
publicboolean isTrueOrYes(String s){
return s.matches("[tT]rue|[yY]es");
}
// Returns true if the string contains exactly "true"
-
8/3/2019 JUnit Eclipse Tutorial
26/46
publicboolean containsTrue(String s){
return s.matches(".*true.*");
}
// Returns true if the string contains of three letters
publicboolean isThreeLetters(String s){
return s.matches("[a-zA-Z]{3}");
// Simpler from for
// return s.matches("[a-Z][a-Z][a-Z]");
}
// Returns true if the string does not have a number at the beginning
publicboolean isNoNumberAtBeginning(String s){
return s.matches("^[^d].*");
}
// Returns true if the string contains a arbitrary number of characters except b
publicboolean isIntersection(String s){
return s.matches("([w&&[^b]])*");
}
// Returns true if the string contains a number less then 300
publicboolean isLessThenThreeHundret(String s){
return s.matches("[^0-9]*[12]?[0-9]{1,2}[^0-9]*" );
}
}
-
8/3/2019 JUnit Eclipse Tutorial
27/46
-
8/3/2019 JUnit Eclipse Tutorial
28/46
assertFalse(m.isTrueVersion2( "true2"));
assertTrue(m.isTrueVersion2( "True"));;
}
@Test
publicvoid testIsTrueOrYes() {
assertTrue(m.isTrueOrYes( "true"));
assertTrue(m.isTrueOrYes( "yes"));
assertTrue(m.isTrueOrYes( "Yes"));
assertFalse(m.isTrueOrYes( "no"));
}
@Test
publicvoid testContainsTrue() {
assertTrue(m.containsTrue( "thetruewithin"));
}
@Test
publicvoid testIsThreeLetters() {
assertTrue(m.isThreeLetters( "abc"));
assertFalse(m.isThreeLetters( "abcd"));
}
@Test
publicvoid testisNoNumberAtBeginning() {
assertTrue(m.isNoNumberAtBeginning( "abc"));
-
8/3/2019 JUnit Eclipse Tutorial
29/46
assertFalse(m.isNoNumberAtBeginning( "1abcd"));
assertTrue(m.isNoNumberAtBeginning( "a1bcd"));
assertTrue(m.isNoNumberAtBeginning( "asdfdsf"));
}
@Test
publicvoid testisIntersection() {
assertTrue(m.isIntersection( "1"));
assertFalse(m.isIntersection( "abcksdfkdskfsdfdsf"));
assertTrue(m.isIntersection( "skdskfjsmcnxmvjwque484242"));
}
@Test
publicvoid testLessThenThreeHundret() {
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"));
}
}
4. Pattern and Matcher
For advanced regular expressions the classes you java.util.regex.Pattern and java.util.regex.Matcher are used.
-
8/3/2019 JUnit Eclipse Tutorial
30/46
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;
publicclass RegexTestPatternMatcher {
publicstaticfinal String EXAMPLE_TEST = "This is my small example string which
I'm going to use for pattern matching.";
publicstaticvoid main(String[] args) {
Pattern pattern = Pattern.compile("w+");
// In case you would like to ignore case sensitivity you could use this
// statement
// Pattern pattern = Pattern.compile("s+", Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(EXAMPLE_TEST);
// Check all occurance
while (matcher.find()) {
System.out.print("Start index: " + matcher.start());
System.out.print(" End index: " + matcher.end() + " ");
System.out.println(matcher.group());
}
// Now create a new pattern and matcher to replace whitespace with tabs
Pattern replace = Pattern.compile("s+");
-
8/3/2019 JUnit Eclipse Tutorial
31/46
Matcher matcher2 = replace.matcher(EXAMPLE_TEST);
System.out.println(matcher2.replaceAll( "t"));
}
}
5. Java Regex Examples
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;
importstatic org.junit.Assert.assertFalse;
importstatic org.junit.Assert.assertTrue;
publicclass EitherOrCheck {
@Test
publicvoid testSimpleTrue() {
String s = "humbapumpa jim";
assertTrue(s.matches(".*(jim|joe).*"));
s = "humbapumpa jom";
assertFalse(s.matches(".*(jim|joe).*"));
s = "humbaPumpa joe";
assertTrue(s.matches(".*(jim|joe).*"));
s = "humbapumpa joe jim";
-
8/3/2019 JUnit Eclipse Tutorial
32/46
assertTrue(s.matches(".*(jim|joe).*"));
}
}
5.2. Phone number
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;
importstatic org.junit.Assert.assertFalse;
importstatic org.junit.Assert.assertTrue;
publicclass CheckPhone {
@Test
publicvoid testSimpleTrue() {
String pattern = "ddd([,s])?dddd" ;
String s= "1233323322";
assertFalse(s.matches(pattern));
s = "1233323";
assertTrue(s.matches(pattern));
s = "123 3323";
assertTrue(s.matches(pattern));
}
}
-
8/3/2019 JUnit Eclipse Tutorial
33/46
5.3. Check for a certain number range
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;
importstatic org.junit.Assert.assertFalse;
importstatic org.junit.Assert.assertTrue;
publicclass CheckNumber {
@Test
publicvoid testSimpleTrue() {
String s= "1233";
assertTrue(test(s));
s= "0";
assertFalse(test(s));
s = "29 Kasdkf 2300 Kdsdf";
assertTrue(test(s));
s = "99900234";
assertTrue(test(s));
}
publicstaticboolean test (String s){
-
8/3/2019 JUnit Eclipse Tutorial
34/46
Pattern pattern = Pattern.compile("d{3}");
Matcher matcher = pattern.matcher(s);
if (matcher.find()){
return true;
}
return false;
}
}
5.4. Building a link checker
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;
-
8/3/2019 JUnit Eclipse Tutorial
35/46
publicclass LinkGetter {
private Pattern htmltag;
private Pattern link;
privatefinal String root;
public LinkGetter(String root) {
this.root = root;
htmltag = Pattern.compile("]*href="[^>]*>(.*?)" );
link = Pattern.compile("href="[^>]*">");
}
public List getLinks(String url) {
List links = new ArrayList();
try {
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(new URL(url).openStream()));
String s;
StringBuilder builder = new StringBuilder();
while ((s = bufferedReader.readLine()) != null) {
builder.append(s);
}
Matcher tagmatch = htmltag.matcher(builder.toString());
while (tagmatch.find()) {
Matcher matcher = link.matcher(tagmatch.group());
-
8/3/2019 JUnit Eclipse Tutorial
36/46
-
8/3/2019 JUnit Eclipse Tutorial
37/46
return link;
}
if (link.matches("/.*") && url.matches(".*$[^/]")) {
return url + "/" + link;
}
if (link.matches("[^/].*") && url.matches(".*[^/]")) {
return url + "/" + link;
}
if (link.matches("/.*") && url.matches(".*[/]")) {
return url + link;
}
if (link.matches("/.*") && url.matches(".*[^/]")) {
return url + link;
}
thrownew RuntimeException("Cannot make the link absolute. Url: " + url
+ " Link " + link);
}
}
JAXB Tutorial
Lars Vogel
Version 1.3
-
8/3/2019 JUnit Eclipse Tutorial
38/46
Copyright 2008 - 2011 Lars Vogel
08.03.2011
Revision History
Revision 0.1 26.02.2008 Lars Vogel
created
Revision 0.2 - 1.3 21.10.2008 - 08.03.2011 Lars Vogel
bug fixes and enhancements
JAXB Tutorial
This tutorial give an introduction to Java Architecture for XML Binding (JAXB). This tutorial is based on Java 6.0.
This article 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.
http://www.vogella.de/articles/JAXB/article.html#overviewhttp://www.vogella.de/articles/JAXB/article.html#overviewhttp://www.vogella.de/articles/JAXB/article.html#jaxbhttp://www.vogella.de/articles/JAXB/article.html#jaxbhttp://www.vogella.de/articles/JAXB/article.html#jaxb_overviewhttp://www.vogella.de/articles/JAXB/article.html#jaxb_overviewhttp://www.vogella.de/articles/JAXB/article.html#jaxb_usagehttp://www.vogella.de/articles/JAXB/article.html#jaxb_usagehttp://www.vogella.de/articles/JAXB/article.html#thankyouhttp://www.vogella.de/articles/JAXB/article.html#thankyouhttp://www.vogella.de/articles/JAXB/article.html#questionshttp://www.vogella.de/articles/JAXB/article.html#questionshttp://www.vogella.de/articles/JAXB/article.html#resourceshttp://www.vogella.de/articles/JAXB/article.html#resourceshttp://www.vogella.de/articles/JAXB/article.html#sourcecodehttp://www.vogella.de/articles/JAXB/article.html#sourcecodehttp://www.vogella.de/articles/JAXB/article.html#resources_xmlhttp://www.vogella.de/articles/JAXB/article.html#resources_xmlhttp://www.vogella.de/articles/JAXB/article.html#resources_generalhttp://www.vogella.de/articles/JAXB/article.html#resources_generalhttp://www.vogella.de/articles/JAXB/article.html#resources_generalhttp://www.vogella.de/articles/JAXB/article.html#resources_xmlhttp://www.vogella.de/articles/JAXB/article.html#sourcecodehttp://www.vogella.de/articles/JAXB/article.html#resourceshttp://www.vogella.de/articles/JAXB/article.html#questionshttp://www.vogella.de/articles/JAXB/article.html#thankyouhttp://www.vogella.de/articles/JAXB/article.html#jaxb_usagehttp://www.vogella.de/articles/JAXB/article.html#jaxb_overviewhttp://www.vogella.de/articles/JAXB/article.html#jaxbhttp://www.vogella.de/articles/JAXB/article.html#overview -
8/3/2019 JUnit Eclipse Tutorial
39/46
The following will explain the JAXB interface, for an introduction into using XML with Java please seeJava XML
tutorial.
2. JAXB 2 - Java Architecture for XML Binding
2.1. Overview
JAXB uses annotations to indicate the central elements.
Table 1.
Annotation Description@XmlRootElement(namespace =
"namespace")
Define the root element for a XML tree
@XmlType(propOrder = { "field2",
"field1",.. })
Allows to define the order in which the fields are written in the XML file
@XmlElement(name = "neuName") 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 a new Java project called "de.vogella.xml.jaxb".
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
@XmlType(propOrder = { "author", "name", "publisher", "isbn" })
http://www.vogella.de/articles/JavaXML/article.htmlhttp://www.vogella.de/articles/JavaXML/article.htmlhttp://www.vogella.de/articles/JavaXML/article.htmlhttp://www.vogella.de/articles/JavaXML/article.htmlhttp://www.vogella.de/articles/JavaXML/article.htmlhttp://www.vogella.de/articles/JavaXML/article.html -
8/3/2019 JUnit Eclipse Tutorial
40/46
publicclass Book {
private String name;
private String author;
private String publisher;
private String isbn;
// If you like the variable name, e.g. "name", you can easily change this
// name for your XML-Output:
@XmlElement(name = "bookName")
public String getName() {
return name;
}
publicvoid setName(String name) {
this.name = name;
}
public String getAuthor() {
return author;
}
publicvoid setAuthor(String author) {
this.author = author;
}
public String getPublisher() {
-
8/3/2019 JUnit Eclipse Tutorial
41/46
return publisher;
}
publicvoid setPublisher(String publisher) {
this.publisher = publisher;
}
public String getIsbn() {
return isbn;
}
publicvoid setIsbn(String 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")
publicclass Bookstore {
// XmLElementWrapper generates a wrapper element around XML representation
@XmlElementWrapper(name = "bookList")
-
8/3/2019 JUnit Eclipse Tutorial
42/46
// XmlElement sets the name of the entities
@XmlElement(name = "book")
private ArrayList bookList;
private String name;
private String location;
publicvoid setBookList(ArrayList bookList) {
this.bookList = bookList;
}
public ArrayList getBooksList() {
return bookList;
}
public String getName() {
return name;
}
publicvoid setName(String name) {
this.name = name;
}
public String getLocation() {
return location;
}
publicvoid setLocation(String location) {
this.location = location;
-
8/3/2019 JUnit Eclipse Tutorial
43/46
}
}
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;
publicclass BookMain {
privatestaticfinal String BOOKSTORE_XML = "./bookstore-jaxb.xml";
publicstaticvoid main(String[] args) throws JAXBException, IOException {
ArrayList bookList = new ArrayList();
// create books
Book book1 = new Book();
book1.setIsbn("978-0060554736");
-
8/3/2019 JUnit Eclipse Tutorial
44/46
book1.setName("The Game");
book1.setAuthor("Neil Strauss");
book1.setPublisher("Harpercollins");
bookList.add(book1);
Book book2 = new Book();
book2.setIsbn("978-3832180577");
book2.setName("Feuchtgebiete");
book2.setAuthor("Charlotte Roche");
book2.setPublisher("Dumont Buchverlag");
bookList.add(book2);
// create bookstore, assigning book
Bookstore bookstore = new Bookstore();
bookstore.setName("Fraport Bookstore");
bookstore.setLocation("Frankfurt Airport");
bookstore.setBookList(bookList);
// create JAXB context and instantiate marshaller
JAXBContext context = JAXBContext.newInstance(Bookstore.class);
Marshaller m = context.createMarshaller();
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
m.marshal(bookstore, System.out);
-
8/3/2019 JUnit Eclipse Tutorial
45/46
Writer w = null;
try {
w = new FileWriter(BOOKSTORE_XML);
m.marshal(bookstore, w);
} finally {
try {
w.close();
} catch (Exception e) {
}
}
// get variables from our xml file, created before
System.out.println();
System.out.println("Output from our XML File: ");
Unmarshaller um = context.createUnmarshaller();
Bookstore bookstore2 = (Bookstore) um.unmarshal(new FileReader(
BOOKSTORE_XML));
for (int i = 0; i < bookstore2.getBooksList().toArray().length; i++) {
System.out.println("Book " + (i + 1) + ": "
+ bookstore2.getBooksList().get(i).getName() + " from "
-
8/3/2019 JUnit Eclipse Tutorial
46/46
+ 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.