Testing a Maven Enterprise Application
This tutorial needs a review. You can edit it in GitHub following these contribution guidelines. |
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.
Tutorial Exercises
To follow this tutorial, you need the following software and resources.
Software or Resource | Version Required |
---|---|
7.4, 8.0, Java EE bundle |
|
version 7 or 8 |
|
GlassFish Server Open Source Edition |
4.0 |
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.
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.
-
Open the Options window in the IDE (Tools > Options; NetBeans > Preferences on Mac).
-
Select the Java category in the Options window and click the Maven tab.
-
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).
-
Click OK to close the Options window.
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.
-
Choose Window > Services to open the Services window.
-
Expand the Maven Repositories node in the Services window.
-
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.
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 Configuring Maven in the Creating a Maven Swing Application Using Hibernate tutorial and also 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.
-
Choose File > New Project (Ctrl-Shift-N; ⌘-Shift-N on Mac) from the main menu to open the New Project wizard.
-
Select Web Application in the Maven category. Click Next.
-
Name the project mavenwebtestapp and set the project location. Click Next.
-
Select the GlassFish Server in the Server dropdown list.
-
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.
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.
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. |
-
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.
-
Type MyEntity for the Class Name.
-
Select
com.mycompany.mavenwebtestapp
as the Package and set the Primary Key Type to *int
*. -
Confirm that Create Persistence Unit is selected. Click Next.
-
Select jdbc/sample in the Data Source dropdown list.
-
Confirm that Use Java Transaction APIs is selected and select Drop and Create as the Table Generation Strategy. Click Finish.
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.
-
In the source editor, add the private field
name
to the class.
private String name;
-
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. -
Add the following constructor.
public MyEntity(int id) {
this.id = id;
name = "Entity number " + id + " created at " + new Date();
}
-
Add the following
@NamedQueries
and@NamedQuery
annotations (in bold) to create a named SQL query that will find all records in the MyEntity table.
@Entity
*@NamedQueries({
@NamedQuery(name = "MyEntity.findAll", query = "select e from MyEntity e")})*
public class MyEntity implements Serializable {
-
Click the hint in the left margin next to the class declaration and choose the Create default constructor hint.
-
Fix the import statements (Ctrl-Shift-I; ⌘-Shift-I on Mac) to add import statements for
javax.persistence.NamedQuery
,javax.persistence.NamedQueries
andjava.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.
-
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.
-
Select Session Beans For Entity Classes in the Enterprise JavaBeans category. Click Next.
-
Select the
MyEntity
class from the list of Available Entity Classes and click Add. Click Next. -
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.
@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);
}
}
-
Add the following methods to
MyEntityFacade.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);
}
}
-
Fix your imports to add the required import statements. Save your changes.
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.
-
Right-click
MyEntityFacade.java
in the Projects window and choose Tools > Create Tests. -
Select a test framework from the Framework dropdown list
-
Use the default options in the Create Tests dialog box. Click OK.
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.
-
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
.
-
Locate the
testVerify
test method in the test class.
You can see that the test contains a line that calls on EJBContainer
.
@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.");
}
-
Make the following changes (in bold) to the skeleton of the
testVerify
test method.
@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();
}
-
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.
-
Open
pom.xml
in the editor and locate the<properties>
element.
<properties>
<endorsed.dir>${project.build.directory}/endorsed</endorsed.dir>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
-
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.
<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>
<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.
|
-
Right-click the Dependencies node in the Projects window and choose Add Dependency.
-
In the Add Dependency dialog box, type embedded-static-shell in the Query text field.
-
Locate the 4.0 JAR in the search results and click Add.
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.
-
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.
<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>
-
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.
-
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 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.
In the Test Results window you can click the Show Passed icon (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.
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
See Also
For more information about using NetBeans IDE to develop Java EE applications, see the following resources:
You can find more information about using Enterprise Beans in the 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, join the nbj2ee mailing list.