// 
//     Licensed to the Apache Software Foundation (ASF) under one
//     or more contributor license agreements.  See the NOTICE file
//     distributed with this work for additional information
//     regarding copyright ownership.  The ASF licenses this file
//     to you under the Apache License, Version 2.0 (the
//     "License"); you may not use this file except in compliance
//     with the License.  You may obtain a copy of the License at
// 
//       http://www.apache.org/licenses/LICENSE-2.0
// 
//     Unless required by applicable law or agreed to in writing,
//     software distributed under the License is distributed on an
//     "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
//     KIND, either express or implied.  See the License for the
//     specific language governing permissions and limitations
//     under the License.
//

= Testing a Maven Enterprise Application
:jbake-type: tutorial
:jbake-tags: tutorials 
:jbake-status: published
:icons: font
:syntax: true
:source-highlighter: pygments
:toc: left
:toc-title:
:description: Testing a Maven Enterprise Application - Apache NetBeans
:keywords: Apache NetBeans, Tutorials, Testing a Maven Enterprise Application

This tutorial demonstrates how to test a simple enterprise application using NetBeans IDE and Maven archetypes. In this tutorial you create an enterprise application that contains an entity class and a session bean. You will use a wizard to create a simple test class for the bean class and then run the test in the IDE. The test class will create an instance of the GlassFish embedded EJB container to test the connection to the database.

NOTE:  If you are using GlassFish 3.1.x, please see link:../../73/javaee/maven-entapp-testing.html[+Testing a Maven Enterprise Application with Embedded GlassFish Server 3.1+]

*Tutorial Exercises*

* <<intro,Using Maven in the IDE>>
* <<Exercise_1,Creating the Enterprise Application>>
* <<Exercise_1a,Creating the Web Project>>
* <<Exercise_1b,Creating the Entity Class>>
* <<Exercise_1c,Creating the Session Bean>>
* <<Exercise_2,Creating the Session Bean Test>>

*To follow this tutorial, you need the following software and resources.*

|===
|Software or Resource |Version Required 

|link:https://netbeans.org/downloads/index.html[+NetBeans IDE+] |7.4, 8.0, Java EE bundle 

|link:http://www.oracle.com/technetwork/java/javase/downloads/index.html[+Java Development Kit (JDK)+] |version 7 or 8 

|GlassFish Server Open Source Edition |4.0 
|===

NOTE:  The installer for GlassFish Server is included when you download the Java EE bundle. You can install and register GlassFish as part of the NetBeans IDE installation process.

*Prerequisites*

This document assumes you have some basic knowledge of, or programming experience with, the following technologies:

* Java Programming
* NetBeans IDE

Before starting this tutorial you may want to familiarize yourself with the following documentation.

* link:http://wiki.netbeans.org/MavenBestPractices[+Best Practices for Apache Maven in NetBeans IDE+]
* link:http://books.sonatype.com/mvnref-book/reference/introduction.html[+Chapter 1. Introducing Apache Maven+] (from link:http://books.sonatype.com/mvnref-book/reference/index.html[+Maven: The Complete Reference +])


== Using Maven in the IDE

Support for Maven is fully integrated in NetBeans IDE. Developing a project that uses the Maven framework is nearly identical to developing a project in Ant. However, there are some differences that are related to the way Maven builds projects and works with dependencies. The following tips can help you avoid some problems if you are creating a Maven application for the first time.

*Check your Maven settings*

If this is your first Maven project you will want to check the Maven configuration settings in the Options window. To complete this tutorial you must have Maven installed on your local system. Maven is bundled with the IDE and installed when you install the IDE.

1. Open the Options window in the IDE (Tools > Options; NetBeans > Preferences on Mac).
2. Select the Java category in the Options window and click the Maven tab.
3. Confirm that a Maven Home is specified.

You can use the Maven version bundled with the IDE or specify the location of a local Maven installation (requires 2.0.9 or newer).


[start=4]
. Click OK to close the Options window.

NOTE:  Maven support is automatically enabled when Java is enabled in the IDE. You will need to enable the Java EE plugin if it is not enabled.

*Update your Maven repositories*

Local and remote Maven repositories are used for code completion and when building projects. You should update the indexes for the Maven remote repositories to ensure that any artifacts you may need are readily available when you develop your project. You can configure how often the IDE checks for updates in the Maven tab of the Options window. You can perform an immediate check for updates and explore your local and remote Maven repositories in the Services window.

1. Choose Window > Services to open the Services window.
2. Expand the Maven Repositories node in the Services window.
3. Right-click the repository node and choose Update Index in the popup menu.

When you click Update Indexes, the IDE will check and download the most recent index for each of your Maven remote repositories. An index represents the current state of the artifacts located in the repository and is used to provide a reference to the artifacts that are available to your application. By default, the IDE does not download an artifact from a repository until the artifact is explicitly required.

NOTE: Indexes are quite large and it can take some time to update them all.

For more details about using Maven in NetBeans IDE, see the section on link:https://netbeans.org/kb/docs/java/maven-hib-java-se.html#02[+Configuring Maven+] in the link:https://netbeans.org/kb/docs/java/maven-hib-java-se.html[+Creating a Maven Swing Application Using Hibernate+] tutorial and also link:http://wiki.netbeans.org/MavenBestPractices[+Best Practices for Apache Maven in NetBeans IDE+].


== Creating the Enterprise Application

In this section you create a simple web application that contains an entity class and a session bean that accesses the entity class.


=== Creating the Web Project

In this exercise you use the New Project wizard to create a Java EE web application from a Maven archetype. When you create the project with the wizard you will specify GlassFish Server as the target server.

1. Choose File > New Project (Ctrl-Shift-N; ⌘-Shift-N on Mac) from the main menu to open the New Project wizard.
2. Select Web Application in the Maven category. Click Next.
3. Name the project *mavenwebtestapp* and set the project location. Click Next.
4. Select the GlassFish Server in the Server dropdown list.
5. Select Java EE 6 Web or Java EE 7 Web in the Java EE Version dropdown list. Click Finish.

When you click Finish the IDE creates the web application and opens the project in the Projects window.

image::images/maven-testing-projects.png[title="Projects window showing generated projects"]

If you expand the project node in the Projects window you can see that the  ``javaee-web-api``  JAR is listed as a project dependency and that the JDK is listed as a Java dependency. The IDE generated the project POM ( ``pom.xml`` ) and the file is listed under the Project Files node.


=== Creating the Entity Class

In this exercise you use the New File wizard to create an entity class. When you create the entity class you will select the  ``jdbc/sample``  datasource in the wizard. You do not need to create or register a new datasource because the  ``jdbc/sample``  datasource was registered when you installed the server.

NOTE:  If you want to create a new datasource or use a different datasource, the datasource must be registered on the server before you test the application using the embedded container. When testing the application using the embedded container the IDE will not register the datasource for you as it does when deploying to a GlassFish server instance.

1. Right-click the project node and choose New > Entity Class.

Alternatively, you can choose File > New File (Ctrl-N; ⌘-N on Mac) from the main menu and select Entity Class in the Persistence category.


[start=2]
. Type *MyEntity* for the Class Name.

[start=3]
. Select  ``com.mycompany.mavenwebtestapp``  as the Package and set the Primary Key Type to * ``int`` *.

[start=4]
. Confirm that Create Persistence Unit is selected. Click Next.

[start=5]
. Select *jdbc/sample* in the Data Source dropdown list.

[start=6]
. Confirm that Use Java Transaction APIs is selected and select Drop and Create as the Table Generation Strategy. Click Finish.

image::images/maven-testing-pu.png[title="Projects window showing generated projects"]

When you click Finish the IDE generates the MyEntity class and opens the class in the source editor. The IDE adds the  ``eclipselink`` ,  ``javax.persistence``  and  ``org.eclipse.persistence.jpa.modelgen.processor``  artifacts as project dependencies.


[start=7]
. In the source editor, add the private field  ``name``  to the class.

[source,java]
----

private String name;
----

[start=8]
. Right-click in the editor and choose Getter and Setter in the Insert Code popup menu (Alt-Insert; Ctrl-I on Mac) to generate a getter and setter for the  ``name``  field.

[start=9]
. Add the following constructor.

[source,java]
----

public MyEntity(int id) {
    this.id = id;
    name = "Entity number " + id + " created at " + new Date();
}
----

[start=10]
. Add the following  ``@NamedQueries``  and  ``@NamedQuery``  annotations (in bold) to create a named SQL query that will find all records in the MyEntity table.

[source,java]
----

@Entity
*@NamedQueries({
    @NamedQuery(name = "MyEntity.findAll", query = "select e from MyEntity e")})*
public class MyEntity implements Serializable {
----


[start=11]
. Click the hint in the left margin next to the class declaration and choose the *Create default constructor* hint.

image::images/maven-testing-createconstructor.png[title="Projects window showing generated projects"]


[start=12]
. Fix the import statements (Ctrl-Shift-I; ⌘-Shift-I on Mac) to add import statements for  ``javax.persistence.NamedQuery`` ,  ``javax.persistence.NamedQueries``  and  ``java.util.Date`` . Save your changes. 


=== Creating the Session Bean

In this exercise you will use a wizard to create a session facade for the  ``MyEntity``  entity class. When you use the wizard to generate the facade the IDE will also generate an abstract facade that contains some methods such as  ``create``  and  ``find``  that are commonly used when accessing entity classes. You will then add two methods to the facade.

1. Right-click the project node and choose New > Other.

Alternatively, you can choose File > New File (Ctrl-N; ⌘-N on Mac) from the main menu to open the New File wizard.


[start=2]
. Select Session Beans For Entity Classes in the Enterprise JavaBeans category. Click Next.

[start=3]
. Select the  ``MyEntity``  class from the list of Available Entity Classes and click Add. Click Next.

[start=4]
. Use the default properties in the Generated Session Beans panel of the wizard. Click Finish.

When you click Finish the IDE generates  ``AbstractFacade.java``  and  ``MyEntityFacade.java``  in the  ``com.mycompany.mavenwebtestapp``  package and opens the classes in the source editor.

In the source editor you can see that the IDE generated code for  ``EntityManager``  and added the  ``@PersistenceContext``  annotation to specify the persistence unit.


[source,java]
----

@Stateless
public class MyEntityFacade extends AbstractFacade<MyEntity> {
    @PersistenceContext(unitName = "com.mycompany_mavenwebtestapp_war_1.0-SNAPSHOTPU")
    private EntityManager em;

    @Override
    protected EntityManager getEntityManager() {
        return em;
    }

    public MyEntityFacade() {
        super(MyEntity.class);
    }
    
}
----

[start=5]
. Add the following methods to  ``MyEntityFacade.java`` .

[source,java]
----

    @PermitAll
    public int verify() {
        String result = null;
        Query q = em.createNamedQuery("MyEntity.findAll");
        Collection entities = q.getResultList();
        int s = entities.size();
        for (Object o : entities) {
            MyEntity se = (MyEntity) o;
            System.out.println("Found: " + se.getName());
        }

        return s;
    }

    @PermitAll
    public void insert(int num) {
        for (int i = 1; i <= num; i++) {
            System.out.println("Inserting # " + i);
            MyEntity e = new MyEntity(i);
            em.persist(e);
        }
    }
----

[start=6]
. Fix your imports to add the required import statements. Save your changes. 

image::images/maven-testing-fiximports.png[title="Projects window showing generated projects"]

NOTE:  Confirm that * ``javax.persistence.Query`` * is selected in the Fix All Imports dialog box.


== Creating the Session Bean Test

In this section you will create a JUnit test class for the  ``MyEntityFacade``  session facade. The IDE will generate skeleton test methods for each of the methods in the facade class as well as each of the methods in the abstract facade. You will annotate the test methods that are generated for the methods in the abstract facade to instruct the IDE and the JUnit test runner to ignore them. You will then modify the test method for the  ``verify``  method that you added to  ``MyEntityFacade`` .

In the generated tests you will see that the IDE automatically adds code that calls on  ``EJBContainer``  to create an instance of the EJB container.

1. Right-click  ``MyEntityFacade.java``  in the Projects window and choose Tools > Create Tests.
2. Select a test framework from the Framework dropdown list
3. Use the default options in the Create Tests dialog box. Click OK.

NOTE:  The first time that you create a JUnit test you need to specify the version of the JUnit framework. Select JUnit 4.x as the JUnit version and click Select.

By default, the IDE generates a skeleton test class that contains tests for each of the methods in  ``MyEntityFacade``  and  ``AbstractFacade`` . The IDE automatically adds a dependency on the JUnit 4.10 to the POM.


[start=4]
. Annotate each of the test methods except  ``testVerify``  with the  ``@Ignore``  annotation. The IDE will skip each of the tests annotated with  ``@Ignore``  when running the tests.

Alternatively, you can delete all the test methods except  ``testVerify`` .


[start=5]
. Locate the  ``testVerify``  test method in the test class.

You can see that the test contains a line that calls on  ``EJBContainer`` .


[source,java]
----

    @Test
    public void testVerify() throws Exception {
        System.out.println("verify");
        EJBContainer container = javax.ejb.embeddable.EJBContainer.createEJBContainer();
        MyEntityFacade instance = (MyEntityFacade)container.getContext().lookup("java:global/classes/MyEntityFacade");
        int expResult = 0;
        int result = instance.verify();
        assertEquals(expResult, result);
        container.close();
        // TODO review the generated test code and remove the default call to fail.
        fail("The test case is a prototype.");
    }
----

[start=6]
. Make the following changes (in bold) to the skeleton of the  ``testVerify``  test method.

[source,java]
----

@Test
public void testVerify() throws Exception {
    System.out.println("verify");
    EJBContainer container = javax.ejb.embeddable.EJBContainer.createEJBContainer();
    MyEntityFacade instance = (MyEntityFacade)container.getContext().lookup("java:global/classes/MyEntityFacade");
    *System.out.println("Inserting entities...");
    instance.insert(5);*
    int result = instance.verify();
    *System.out.println("JPA call returned: " + result);
    System.out.println("Done calling EJB");
    Assert.assertTrue("Unexpected number of entities", (result == 5));*
    container.close();
}
----

[start=7]
. Fix the import statements to add  ``junit.framework.Assert`` . Save your changes.

You now need to modify the POM to add a dependency on the  ``<glassfish.embedded-static-shell.jar>``  that is located in your local installation of the GlassFish server.


[start=8]
. Open  ``pom.xml``  in the editor and locate the  ``<properties>``  element.

[source,xml]
----

    <properties>
        <endorsed.dir>${project.build.directory}/endorsed</endorsed.dir>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>
                
----

[start=9]
. Edit the  ``<properties>``  element to add the  ``<glassfish.embedded-static-shell.jar>``  element (in *bold*) that specifies the location of the JAR in your local GlassFish installation. You will then reference this property in the dependency on the artifact.

[source,xml]
----

    <properties>
        <endorsed.dir>${project.build.directory}/endorsed</endorsed.dir>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        *<glassfish.embedded-static-shell.jar>_<INSTALLATION_PATH>_/glassfish-4.0/glassfish/lib/embedded/glassfish-embedded-static-shell.jar</glassfish.embedded-static-shell.jar>*

    </properties>
                
----

NOTE:   ``_<INSTALLATION_PATH>_``  is the absolute path to your local GlassFish installation. You will need to modify this element in the POM if the path to the local installation changes.


[start=10]
. Right-click the Dependencies node in the Projects window and choose Add Dependency.

[start=11]
. In the Add Dependency dialog box, type *embedded-static-shell* in the Query text field.

[start=12]
. Locate the 4.0 JAR in the search results and click Add.

image::images/add-shell-dependency.png[title="Test Results window"]

When you click Add the IDE adds the dependency to the POM.

You now want to modify the POM to specify the local installation of GlassFish as the source for the JAR.


[start=13]
. Locate the dependency in the POM and make the following changes (in *bold*) to modify the element to reference the  ``<glassfish.embedded-static-shell.jar>``  property that you added and to specify the  ``<scope>`` . Save your changes.

[source,xml]
----

        <dependency>
            <groupId>org.glassfish.main.extras</groupId>
            <artifactId>glassfish-embedded-static-shell</artifactId>
            <version>4.0</version>
            *<scope>system</scope>
            <systemPath>${glassfish.embedded-static-shell.jar}</systemPath>*
        </dependency>
                
----

[start=14]
. In the Services window, right-click the GlassFish Server node and choose Start.

The JavaDB database server will also start when you start the GlassFish Server.


[start=15]
. In the Projects window, right-click the project node and choose Test.

When you choose Test the IDE will build application and run the test phase of the build lifecycle. The unit tests will be executed with the surefire plugin, which supports running JUnit 4.x tests. For more about the surefire plugin, see link:http://maven.apache.org/plugins/maven-surefire-plugin/[+http://maven.apache.org/plugins/maven-surefire-plugin/+].

You can see the results of the test in the Test Results window. You can open the Test Results window by choosing Window > Output > Test Results from the main menu.

image::images/maven-test-results.png[title="Test Results window"]

In the Test Results window you can click the Show Passed icon (image:images/test-ok_16.png[title="Show Passed icon"]) to display a list of all the tests that passed. In this example you can see that nine tests passed. If you look in the Output window you can see that only one test was run and eight tests were skipped. Skipped tests are included in the list of tests that passed in the Test Results window.


[source,java]
----

Running com.mycompany.mavenwebtestapp.MyEntityFacadeTest
verify
...
Inserting entities...
Inserting # 1
Inserting # 2
Inserting # 3
Inserting # 4
Inserting # 5
Found: Entity number 2 created at Wed Oct 09 19:06:59 CEST 2013
Found: Entity number 4 created at Wed Oct 09 19:06:59 CEST 2013
Found: Entity number 3 created at Wed Oct 09 19:06:59 CEST 2013
Found: Entity number 1 created at Wed Oct 09 19:06:59 CEST 2013
Found: Entity number 5 created at Wed Oct 09 19:06:59 CEST 2013
JPA call returned: 5
Done calling EJB
...

Results :

Tests run: 9, Failures: 0, Errors: 0, Skipped: 8

----


link:/about/contact_form.html?to=3&subject=Feedback:%20Creating%20an%20Enterprise%20Application%20Using%20Maven[+Send Feedback on This Tutorial+]



== See Also

For more information about using NetBeans IDE to develop Java EE applications, see the following resources:

* link:javaee-intro.html[+Introduction to Java EE Technology+]
* link:javaee-gettingstarted.html[+Getting Started with Java EE Applications+]
* link:maven-entapp.html[+Creating an Enterprise Application Using Maven+]
* link:../../trails/java-ee.html[+Java EE &amp; Java Web Learning Trail+]

You can find more information about using Enterprise Beans in the link:http://download.oracle.com/javaee/6/tutorial/doc/[+Java EE 6 Tutorial+].

To send comments and suggestions, get support, and keep informed on the latest developments on the NetBeans IDE Java EE development features, link:../../../community/lists/top.html[+join the nbj2ee mailing list+].

