Showing posts with label Unit Testing and Integration Testing. Show all posts
Showing posts with label Unit Testing and Integration Testing. Show all posts

Wednesday, January 4, 2012

JUnit 4.10 - Writing your first JUnit 4 test in a TDD Approach

In this article I will show you how to write your first JUnit 4 test.I will use Test Driven Development Approach (TDD from here onwards). This means I will first write an empty method to test. Then I will write the Test Class which will test this method. This of course means that the test will fail. Then once we know what we want from the test, we then refactor our actual method. This is exactly how it works in a TDD approach. We write the test first, then it fails, then we discover what needs to be refactored and we make the change in the class to test.

I will not use any IDE. A simple text editor like Notepad++ will suffice. This is in Windows environment.

  1. Download JUnit 4.10 source from here.

  2. Extract to C:\JUnit4.10.

  3. Add C:\JUnit4.10\junit-4.10.jar to CLASSPATH. Also make sure your JAVA_HOME variable is configured properly. Add your JAVA_HOME folder path to CLASSPATH as well since we will be compiling classes from command prompt.

  4. Now you are ready to write your first class.Since we are going to follow Test Driven Development, we will simply create a stub of the method we want to test.
    So go ahead and create a simple class called Calculator.java

    public class Calculator{

        public int add(int a, int b){
            return null;
        }

    }


    You notice that the method add, which we will test, returns null. This is a very simple test and you can figure out that it should return a + b. But this being TDD approach, we will not write this method. We actually want this method to fail. Now we are ready to write our Test Class.

  5. Go ahead and write the Test Class. We will call it CalculatorTest.java

    import static org.junit.Assert.*;
    import org.junit.Test;

    public class CalculatorTest{

        @Test
        public void testAdd()
        {
            Calculator calc = new Calculator(); //Setup object to Test
            int result = calc.add(2,8); //Call the method to Test
            assertEquals(10, result, 0); //Verify        
        }

    }


    The first thing to note is that I have annotated the method testAdd() with @Test. This is significant. The test suite will specifically look for methods with @Test in order to test it. Also note that test methods are void and the convention is to write testXX() where 'XX' is the name of the method to test.

    In any test method, you will first instantiate (by creating a new object in our case or use DI) the object to test. You would then set all the defaults of the object. In our case, there isn't any. This is the setup portion. You setup the object to test. Next you will call the method to test which may or may not return something. In our case it does. If it does not return, you can simply verify that the method has been called and that there is no exception. Finally, you assert or verify that the outcome is what you expect.

  6. Compile both classes from the command prompt using javac Calculator.java and javac CalculatorTest.java. Both should compile.

  7. Run the test from the command prompt again using java org.junit.runner.JUnitCore CalculatorTest


  8. You will get a Test Failed Error
    .

  9. Now you are ready to refactor!
    You know that your Calculator class needs to return the sum of the two passed-in integers by looking at the test. So you make that change.

    public class Calculator{

        public int add(int a, int b){
            return a+b;
        }

    }



  10. Repeat 6 and 7. You will now get a Test Passed message.


 

This is a very simple test. But think of a scenario when you have to test a very complex method. Even better think of a scenario where your method is tied up with resources(values) from your configuration file that you may not be able to access(acquire) in your local development environment. But you still need to write the method correctly before you can check-in the code. In such a scenario, you will mock out the object in the test class. This will ensure that your method is fully tested and what values of the mocked object you need from the configuration. At the very least, you will know how the method should actually work because tests should be informative.

I will be writing more on testing DAOs and Service layers (mocking) in the future. As usual, I appreciate your comments.

 

Thursday, June 9, 2011

Unit Testing Hibernate Data Access Objects using JUnit 4 – Part II

In part I we setup the infrastructure or the framework for unit testing. In this part we will write out domain/entity class, dao interface, dao implementation test and then dao implementation. When we write our test we know it will fail because no such method will exist in the dao implementation. However, we will need to create the implementation class, albeit without any methods. So, let's get straight to it.

@Entity
public class Item {

@Id@GeneratedValue(strategy=GenerationType.AUTO)
private Long id;

@ManyToOne
private Order order;
private String product;
private double price;
private int quantity;
/**
* @return the id
*/
public Long getId() {
return id;
}

/**
* @return the order
*/
public Order getOrder() {
return order;
}
// --- getters and setters follow.
//--- override the ToString()and HashCode()

public class Order{

//Other instance variables ....
@OneToMany(cascade=CascadeType.ALL)
@JoinColumn(name="ORDER_ID")
private Collection items = new LinkedHashSet();

/**
* @return the items
*/
public Collection getItems() {
return items;
}
/**
* @param items the items to set
*/
public void setItems(Collection items) {
this.items = items;
}
}


Few things to note here if you are using hibernate are ITEM has many to one relationship with ORDER- an order has many items whereas an item belongs to an order. In the database you will have ORDER_ID column in the ITEM table. Cascade.ALL means whenever ORDER is deleted, corresponding ITEM is set to null. We will not update the id of ORDER because it is auto-generated. So update to an ORDER does not have any bearing on ITEM. The ids are auto-generated.

Now that we have our domain objects, we will write ItemDao. You will similarly write OrderDao, but  I will leave that to you.

public interface ItemDao {

/**
* Given an item id
* return the Item object.
* @param id of the
* @return Matching Item object.
*/
public Item findById(Long itemId);

/**
* @return All items
*/
public List<Item> findAllItems();
}


We have two simple methods to find an Item by item id and findAllItems. You would indeally expand on this and write methods to delete, update, findItemByOrderId and so on. For now, let's keep things simple.

Now we will implement this dao, except we will return null from the implemented methods.

public class ItemDaoImpl implements ItemDao {

public Item findById(Long itemId){
return null;
}

public List<Item> findAllItems() {
return null;
}
}


We can now write our unit test! If you've followed part I, we setup application-context to inject dao implementation. Now we will read the application-context in order to inject that. Also I mentioned that the test methods will be annotated with @Transactional. This is to ensure that when the method returns (void), the transactions within will be rolledback. This is to ensure that our test db will remain unchanged and we can test again and again with same test data. Of course, this also means that you will need to populate your test data. So let's do that first.

Run this query in MySQL and you will have 2 rows in the ITEM table.

INSERT INTO `test_hibernate`.`item` (
`ID` ,
`PRODUCT` ,
`PRICE` ,
`QUANTITY` ,
`ORDER_ID`

)
VALUES (
NULL , 'Sony Headphones', '99.99', '3', NULL

), (
NULL , 'Logitech XZ Mouse', '15.99', '2', NULL

);


For now we don't set ORDER_ID. Now that you have two rows, we can write our tests.

@ContextConfiguration(locations={"classpath:/applicationContext.xml"})
@RunWith(SpringJUnit4ClassRunner.class)
public class ItemDaoImplTest {

@Autowired
private ItemDaoImpl dao;

@Test
@Transactional
public void testFindById()
{
Item newItem =  dao.findById(1L);
assertTrue(newItem.getProduct().equals("Sony Headphones"));
}

@Test
@Transactional
public void testFindAllItems()
{
List<Item> itemList = dao.findAllItems();
assertTrue(String.valueOf(itemList.size()).equals("2"));
}

If you run this now, your tests will fail. This is because you have not implemented the methods correctly.

So now, we implement those methods from daoImpl.

public Item findById(Long itemId){
DetachedCriteria itemCriteria = DetachedCriteria.forClass(Item.class);
itemCriteria.add(Restrictions.eq(ID_FIELD, itemId));
List<Item> itemList = findByCriteria(itemCriteria);
if(null != itemList && itemList.size() > 0)
return itemList.get(0);
return null;
}

public List<Item> findAllItems() {
DetachedCriteria itemCriteria = DetachedCriteria.forClass(Item.class);
List<Item> itemList = findByCriteria(itemCriteria);
if(null != itemList && itemList.size() > 0)
return itemList;
return null;
}

As I mentioned in part I, I will use DetachedCriteria to query our database. One subtle advantage of doing this is constructing queries is easy (to read and write) and the other major advantage would be since we are going to call this from another module most likely, for example web application's controller via service method in this module, we want the session to be started only when the dao method is called and to be cleaned up as soon as the method returns.

Run the test again, and it will pass. This takes care of testing dao. In a near future I will show you how to write tests for service methods by mocking out the db. I will also point out the advantage of doing this.

Monday, June 6, 2011

Unit Testing Hibernate Data Access Objects using JUnit 4 - Part I

In this article, I want to show you how to write unit tests for your DAOs. You would preferably use an in-memory db instance like HsqlDb but using a test db is perfectly fine since you're going to rollback each db transaction. One thing to remember while doing a DAO unit test is that you'd want to test with the db provider that you are going to use in the live, except you will use a test db instance and not the live db instance. The reason for this is that let's say you are using Hibernate just like I am doing here. You would want to test whether or not the sql queries run against the db using the specific version of hibernate works. Hibernate ships with different versions of driver classes for different db vendors, but for some reason, let's say the encoding of the db you're going to use in the live version does not support certain SQL queries generated by Hibernate. If you do an in-memory HSQLDB test and pass you will most likely think that will work with your specific version of db provider. I just don't think this is accurate enough especially if your queries are complex joins. Again, the rollback feature works for you to take advantage of and regardless of whether you are using an in-memory instance or not, you would still need to populate some data before testing. How else would you test find methods? Another advice I would like to give is to try and use accurate data. I don't mean real-values of credit cards, but data not like "AAAA" in place of a person's name. You may run into various issues later when populating your test db with such data. One such problem I can think of is if your entities are annotated with column specifications such as length and type and you have added data that may not be 100% compatible with that. Another problem is relationships between entities.

Moving on we will have these steps:

1. Pre-requisites
2. Setting up the application context
3. Writing Domain and DAO interface
4. Writing DAO unit tests
5. Writing DAO implementations

I will cover 1 and 2 in this part to have the framework in place. In the next part we will write our domain (just one) and dao interface, dao unit test and then dao implementation. This is a logical order because we would want to test first an then see what we need in order for the test to pass. That 'what we need' will go into our implementation. This is called, as you might have guessed it, Test Driven Approach.

Pre-requisites

* Spring Core library for dependency injection. We are also going to use SpringJunit4ClassRunner for unit testing.
* Hibernate 3.x. We will be using Hibernate's Criteria, specifically, Detached Criteria. For more info on using Criteria look here.
* MySQL db.

You can use Maven to configure all of these. Here's what part of the pom.xml looks like. If you need more help on configuring a maven project please look at my "How to setup a Maven Java Enterprise Application". You can find that under the category "Deployment". Here's the list of artifacts you'll need:

<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.2.2</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>3.3.2.GA</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-annotations</artifactId>
<version>3.3.1.GA</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-commons-annotations</artifactId>
<version>3.3.0.ga</version>
</dependency>
<dependency>
<groupId>javassist</groupId>
<artifactId>javassist</artifactId>
<version>3.6.0.GA</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-jcl</artifactId>
<version>1.5.8</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.16</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.framework.version}</version> <!--version 3.0.5.RELEASE -->
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.framework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${spring.framework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.framework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${spring.framework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${spring.framework.version}</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.14</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.7</version>
</dependency>


Setting up the Application Context

When the test is run, it will scan the application context to inject the dao interface. The implementation of the dao interface will use Hibernate's sessionFactory to run our Hibernate queries. We will also add our single Item domain/entity to use sessionFactory. That object will be directly mapped to the ITEM table of our db. I will not create the table since this is simple enough. Lastly, we will need to use Transactions in order to rollback our unit test methods. For this, we will annotate our test methods as @Transactional. Below is the applicationContext.xml.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  xmlns:tx="http://www.springframework.org/schema/tx"     xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">

<!--  This is where the properties related to datasource are read from -->
<bean id="propertyConfigurer">
<property name="location" value="classpath:hibernate.properties" />
<property name="ignoreUnresolvablePlaceholders" value="false" />
</bean>

<!--  Define dataSource to use -->
<bean id="dataSource">
<property name="driverClassName" value="${hibernate.jdbc.driver}" /> <!-org.gjt.mm.mysql.Driver -->
<property name="url" value="${hibernate.jdbc.url}" />
<property name="username" value="${hibernate.jdbc.user}" />
<property name="password" value="${hibernate.jdbc.password}" />
</bean>

<!--  The sessionFactory will scan the domain objects and their annotated relationships. -->
<bean id="sessionFactory">
<property name="dataSource" ref="dataSource" />
<property name="annotatedClasses">
<list>
<value>com.company.application.core.domain.Item</value>
..............
</list>
</property>
<property name="schemaUpdate" value="true" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.connection.isolation">2</prop>
<prop key="hibernate.bytecode.use_reflection_optimizer">true</prop>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.jdbc.batch_size">20</prop>
<prop key="hibernate.max_fetch_depth">2</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">true</prop>
</props>
</property>
</bean>

<!--  Define Transaction Manager. We will use Hibernate Transaction Manager. -->

<bean id="transactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<!--  We will set transactional properties with annotation -->
<tx:annotation-driven />
<bean id="itemDao">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
</beans>


One thing you might have noticed is that I could easily annotated my Dao as @Resource, have it scanned and not defined in the xml above. That is perfectly legal. Now we're set to write our domain, dao interface, dao test and dao implementation.

Tuesday, May 31, 2011

Setting up Maven Enterprise Application Part II

Part II: Setting up individual modules of an EAR






If you've been following along, this is part 2 of two part series in setting up Maven Enterprise Application. Here is part I which shows you how to use maven to setup the overall project structure, configure build path, add module dependencies and libraries. In this second part, I will show you how to structure the individual modules, the JAR and WAR. Since I've assumed that you're using Eclipse/RAD or any other IDE for that matter, I've already discussed how to add WAR to the EAR in part I. From the IDE this is basically adding WAR module dependency to EAR.

Overall View
Before I begin, please see the image below from RAD to see the overall structure. For some of you, this should be enough. You can get this view from Enterprise Explorer in RAD or Project Explorer in Eclipse. Some of you may prefer to use Navigator window. But I am more comfortable with the former two.

[caption id="attachment_53" align="alignnone" width="211" caption="Module Structure"]module_structure[/caption]

JAR Module

The JAR Module will, as I mentioned in Part I, house your model and unit tests for the models. Your model will consist of domains, daos which are your db technology dependent interface and services which are your business interfaces and not underlying db specific. Additionally, you may have custom exception or helper classes.

Your source folder will be under src/main/java. Any resources like perhaps an applicationContext file will be added to src/main/resources. In part I, I mentioned that these locations are added to the classpath. So to read any resource from there you'd write something like classpath*:applicationContext.xml.
Your unit tests (unit tests for JAR module and integration tests for WAR module) will be housed under src/test/java and any resource like applicationContext file will be housed under src/test/resources.

Basically, if you use an ORM tool your domains or entities define relationships and constraints. These domains are package under com.yourComanpyName.applicationName.domain package. You don't write tests for domain objects. Your dao interfaces are packaged under com.yourComanpyName.applicationName.dao and the implementations are packaged under com.yourComanpyName.applicationName.dao.impl. If you're using spring for dependency injection, you'd annotate the implentations as @Repository or define a bean in the application_context.xml file. You would then be able to Autowire your daos to your service and service unit tests. Now daos will have to be unit tested. Therefore you'd create a new package for the tests as com.yourComanpyName.applicationName.dao.impl (same package) under src/test/java. I am not going into details of writing unit tests and daos or any code in this two part series. I will have articles on them later. Now your service methods will be structured similarly to your daos under com.yourComanpyName.applicationName.service and com.yourComanpyName.applicationName.service.impl. You'd want to use DI to initialize them via annotation or xml the same way you'd do for daos because these service methods will be called from WAR module. Your tests for service will go under com.yourComanpyName.applicationName.service.impl under src/test/java. For unit testing you'd want to use a mocking tool like EasyMock or Mockito. You want to mock out the service tests because you do not want to tie up your service to a specific dao implementation. For example, tomorrow you might change from hibernate to using iBatis or JDBC.

So this is basically it as far as your JAR module goes.

WAR Module

The war module will follow the same naming convention as the JAR module. Your sources will be housed under src/main/java and the resources (not web.xml) will be housed under src/main/resources. You can have a folder called WebContent (exists by default in RAD's dynamic application) under which you will have your WEB-INF folder for your web descriptor file (web.xml), static folder for your pages, scripts, css and images. Your tests for source files will be under src/main/test as usual.

Suppose you're using Struts 2, you would then have the action (controllers in Struts 2) classes under com.yourComanpyName.applicationName.web.action package. This is sticking to the naming convention. Your actions will call your injected service interfaces from the JAR module. Your applicationContext file will almost always be the same as what you defined in the JAR module.

Now you'd want to do integration tests in WAR module. The package to create would be the same as for your Action classes (or controllers) but under src/main/test. For integration testing, you'd use a tool to mock out the HttpServletRequest and Session. You can also mock out the db as you did in the service unit tests in the JAR module. That way you are not dependent on dao implementation.

The only thing remaining is to add JAR module as dependency to the WAR module. This I explained in part I. But it is pretty straightforward from the IDE.

You are now all set to start working on your EAR project.

Final Note: I have not covered unit testing or integration testing in any detail for you to be able to go ahead and start writing them. The purpose was only to show you how to setup an EAR using maven. I will have articles related to them later. But the good part is that I won't have to explain the folder structures then. I can always refer to these two articles :)

 

Monday, May 30, 2011

Setting Up Maven Enterprise Application Part I

Part I: Setting up maven and overall structure






This will be the first of 2 part series where I would like to show how to quickly setup a Java Enterprise Application. In this part you will setup the overall project structure, configure your libraries, build path and module dependencies. I use RAD/Eclipse with m2Eclipse plugin which you can find here for development but the configuration is independent of what IDE or text editor you choose to use. So let's get started.

Pre-requisites:

  • Maven 2. I used maven version 2.0.9. For a higher version of maven, please refer to maven documentation.

  • Eclipse/RAD. Although you can do this without an IDE, it will nonetheless be easier to configure in an IDE since this is an Enterprise Application.

  • JDK 1.4 or higher. I prefer JDK 5 or higher.


Overall structure
The enterprise application that I am going to setup will have a JAR module for services and DAOs, a WAR module that will import the JAR module and an EAR module that will include the WAR module. If you wish to add more modules, you can choose similar structure. You could have only WAR and JAR modules in eclipse, but it is preferable to house them within an EAR. Also RAD requires you to have a deployable EAR. Our WAR module will be deployed. To make this a maven project will have also have a parent-pom (which is not a module) sit above all three modules above that will package them together.

Look at the structure below to see how the structure will look like:
Overall Structure

Setting individual modules starting with parent-pom
When you look at the image above, you will see three files: pom.xml, .project, .classpath. All three are important to configure. The IDE will generate your .classpath and .project files but I will nevertheless go through all of them to ensure that you understand what the IDE is generating. Also you can the .settings folder. This folder is specifically related to parent-pom. This folder will contain additional project/IDE related configurations. But I will not go through this because I don't want to make this too long. Also, the configuration for individual modules will be similar to what you will do for parent-pom. If you understand how I am going to configure these three files, you will easily be able to configure the rest.
So let's begin with pom.xml. Pom files are read by maven in order to do the following:

  • Package modules. In this parent pom, you will package all three modules. The package name will be their folder names. In the EAR's pom, you would add the WAR module and in the WAR the JAR module. The JAR module will not have any module dependency.

  • Define versioning, application description, url, name and so on. This is self explanatory. However, you'd want version to be consistent across all modules.

  • Dependencies. You will define all the artifacts and their version that you'd use in your application. In this parent pom, you'd define all artifacts that are common to more than one module. For e.g you'd define log4j here since you'd need logging in both the JAR and WAR module. Same can be said of JUnit and Spring core libraries.

  • Developers and Contributors. Optional. List out the developers/contributors and their roles.

  • Plugin Lists. This lets you define your goals for you build process. For example, you'd use cobertura to see what percentage of your source code is unit tested.

  • Reporting List. Optional. If your need is to generate reports, you'd use this. Again, as I mentioned you'd want to get cobertura report, here's where you define cobertura-maven-plugin.

  • Repositories. A repository is where you'd pull all the artifacts from. Some private repos need authentication, but most don't. While your default settings.xml of maven is a good place to define your repositories, this is also another place to do so.


Please look at the code below for more info:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<!--
This is the 'parent' POM (Project Object Model) which will have the following
nodes inherited by any POM which declared the <parent/> node to point to this
POM. Please note: This is not the 'super POM' which is supplied by Maven itself.
The super POM has its values inherited by all POMs.

* dependencies
* developers and contributors
* plugin lists
* reports lists
* plugin executions with matching ids
* plugin configuration

@author yourName
@version 1.0
-->

<!--
The POM version.
-->
<modelVersion>4.0.0</modelVersion>

<!--
The organization that is creating the artifact. The standard naming convention
is usually the organizations domain name backwards like the package name in Java.
-->
<groupId>com.yourCompanyName.ApplicationName</groupId>

<!--
The artifact name. This will be used when generating the phsyical artifact name.
The result will be artifactId-version.type.
-->
<artifactId>parent-pom</artifactId>

<!--
The type of artifact that will be generated. In this case no real artifact is
generated by this POM, only the sub projects.
-->
<packaging>pom</packaging>

<!--
The version of the artifact to be generated.
-->
<version>0.0.1-SNAPSHOT</version>

<!--
The name of the project to be displayed on the website.
-->
<name>Your Application Name</name>

<!--
The description of the project to be displayed on the website.
-->
<description>
Description of your app
</description>

<!--
The url of the project to be displayed on the website.
-->
<url>http://www.WARModuleURL.com</url>
<!--
This project is an aggregation/multi-module which includes the following
projects. Please note: the value between the module node is the folder
name of the module and not the artifactId value.
-->
<modules>
<module>AppNameJAR</module>
<module>AppNameWAR</module>
<module>AppNameEAR</module>
</modules>

<!--
This segement list the inherited dependencies for each child POM.
-->
<dependencies>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>1.8.5</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.4</version>
<scope>test</scope>
</dependency>
......
</dependencies>

<!--
The following node defines the developers that are working on the project,
their roles and contact information. This will be used when the site is
generated for the project. (mvn site).

* id - The id of the developer.
* name - The display name that will be used for the display name under 'Project Team' of the website.
* email - The e-mail address of the team member which will be displayed.
* roles - A list of roles the member fulfills.
* organization - The organization of the developer.
* timezone - The timezone of the developer.
-->
<developers>
<developer>
<id>12344</id>
<name>Your Name</name>
<email>yourEamil</email>
<organization>
ABC company INC
</organization>
<organizationUrl>http://www.ABC_Comapnycom</organizationUrl>
<roles>
<role>Technical Leader</role>
</roles>
<timezone>+5:45</timezone>
</developer>
</developers>

<!--
The following node defines the contributors that are working on the project,
their roles and contact information. This will be used when the site is
generated for the project. (mvn site).

* name - The display name that will be used for the display name under 'Project Team' of the website.
* email - The e-mail address of the team member which will be displayed.
* roles - A list of roles the member fulfills.
* organization - The organization of the developer.
* timezone - The timezone of the developer.
-->
<contributors>
<contributor>
<name>SomeName</name>
<email>SomeEmail</email>
<organization>
ABC company INC
</organization>
<organizationUrl>http://www.ABC_Comapnycom</organizationUrl>
<roles>
<role>Engineering Manager</role>
</roles>
<timezone>+5:45</timezone>
</contributor>
...
</contributors>
<!--
Each POM file is a configuration file for the build process. There are many plug-ins
for adding new steps in the build process and controlling which JDK is being used.
Below we customize the version of the JDK as well as some code inspection tools like:

1. Cobertura
-->
<build>
<plugins>
<!--
Configure the maven-compiler-plugin to use JDK 1.5
-->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.5</source>
<target>1.5</target>
<fork>true</fork>
</configuration>
</plugin>
<!--
Configure Cobertura to ignore monitoring the apache log4j
class.
-->
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>cobertura-maven-plugin</artifactId>
<version>2.0</version>
<configuration>
<instrumentation>
<ignores>
<ignore>org.apache.log4j.*</ignore>
</ignores>
</instrumentation>
</configuration>

<!--
The following controls under which goals should this
plug-in be executed.
-->
<executions>
<execution>
<goals>
<goal>clean</goal>
<goal>cobertura</goal>
</goals>
</execution>
</executions>
</plugin>

<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>findbugs-maven-plugin</artifactId>
<version>2.0.1</version>
<configuration>
<findbugsXmlOutput>true</findbugsXmlOutput>
<includeTests>false</includeTests>
<skip>true</skip>
</configuration>

</plugin>

<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<configuration>
<descriptors>
<descriptor>assembly.xml</descriptor>
</descriptors>
</configuration>
</plugin>

</plugins>
</build>

<!--
Maven can look at various repositories to locate dependencies that
need to be downloaded and placed into the local repository. In the
below configuration, we enable codehaus, apache, and opensymphony
repositories.
-->
<repositories>
<repository>
<id>snapshots-maven-codehaus</id>
<name>snapshots-maven-codehaus</name>
<snapshots>
<enabled>true</enabled>
<updatePolicy>always</updatePolicy>
<checksumPolicy>ignore</checksumPolicy>
</snapshots>
<releases>
<enabled>false</enabled>
</releases>
<url>http://snapshots.maven.codehaus.org/maven2</url>
</repository>
<repository>
<id>Maven Snapshots</id>
<url>http://snapshots.maven.codehaus.org/maven2/</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
<releases>
<enabled>false</enabled>
</releases>
</repository>
<repository>
<id>spring-s3</id>
<name>Spring Portfolio Maven MILESTONE Repository</name>
<url>
http://s3.amazonaws.com/maven.springframework.org/milestone
</url>
</repository>
...
</repositories>

<!--
For the reporting area of the website generated.

1. JavaDoc's
2. SureFire
3. Clover
4. Cobertura
5. JDepend
6. FindBugs
7. TagList

-->
<reporting>
<plugins>
<plugin>
<artifactId>maven-javadoc-plugin</artifactId>
<configuration>
<reportOutputDirectory>${site-deploy-location}</reportOutputDirectory>
<destDir>${project.name}</destDir>
<aggregate>true</aggregate>
</configuration>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>jxr-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>surefire-report-maven-plugin</artifactId>
</plugin>
<plugin>
<artifactId>maven-clover-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>cobertura-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>jdepend-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>findbugs-maven-plugin</artifactId>
<version>1.0.0</version>
<configuration>
<threshold>Normal</threshold>
<effort>Default</effort>
</configuration>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>taglist-maven-plugin</artifactId>
<configuration>
<tags>
<tag>TODO</tag>
<tag>FIXME</tag>
<tag>@todo</tag>
<tag>@deprecated</tag>
</tags>
</configuration>
</plugin>
</plugins>
</reporting>

</project>

Now that this is taken care of let's look into .project and .classpath quickly. The .project basically specifies build Commands. We will use eclipse's javaBuilder and maven2Builder. Look below.

<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>parent-pom</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.maven.ide.eclipse.maven2Builder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.jdt.core.javanature</nature>
<nature>org.maven.ide.eclipse.maven2Nature</nature>
</natures>
</projectDescription>


.classpath is where you'd define where you want the built packages to reside, your maven repository location, what your source files are and the path to them are. Here's one from the WAR module.

<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="src" output="target/classes" path="src/main/java"/>
<classpathentry kind="src" output="target/classes" path="src/main/resources"/>
<classpathentry kind="src" output="target/test-classes" path="src/test/java"/>
<classpathentry kind="src" output="target/test-classes" path="src/test/resources"/>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/J2SE-1.5"/>
<classpathentry kind="con" path="org.eclipse.jst.j2ee.internal.web.container"/>
<classpathentry exported="true" kind="con" path="org.eclipse.jst.j2ee.internal.module.container"/>
<classpathentry kind="con" path="org.eclipse.jst.server.core.container/com.ibm.ws.ast.st.runtime.runtimeTarget.v61/was.base.v61"/>
<classpathentry kind="con" path="org.maven.ide.eclipse.MAVEN2_CLASSPATH_CONTAINER"/>
<classpathentry kind="output" path="target/classes"/>
</classpath>


At this stage you have setup the overall project structure, configured your libraries, build path and module dependencies. You are now ready to build individual modules starting with your JAR, then WAR and finally adding them to EAR. You basically add JAR to WAR and only add WAR to EAR. You don't want cycilc dependency. I will show this in part II.