blob: d5210719fda607d8982a184217168f559a015a98 [file] [log] [blame]
<!doctype html>
<html class="no-js" lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<title>Using the Embedded EJB Container to Test Enterprise Applications</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="Using the Embedded EJB Container to Test Enterprise Applications - Apache NetBeans">
<meta name="author" content="Apache NetBeans">
<meta name="description" content="Using the Embedded EJB Container to Test Enterprise Applications - Apache NetBeans">
<meta name="keywords" content="Apache NetBeans, Tutorials, Using the Embedded EJB Container to Test Enterprise Applications">
<meta name="generator" content="Apache NetBeans">
<link rel="stylesheet" href="../../../../../../_/css/font-awesome.min.css">
<link rel="alternate" type="application/atom+xml" title="Apache NetBeans Blog" href="https://netbeans.apache.org/blogs/atom" />
<link rel="stylesheet" href="../../../../../../_/css/highlightjs/default.min.css">
<link rel="stylesheet" href="../../../../../../_/css/netbeans.css">
<link rel="apple-touch-icon" sizes="180x180" href="../../../../../../_/images/fav/apple-touch-icon.png">
<link rel="icon" type="image/png" sizes="32x32" href="../../../../../../_/images/fav/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="16x16" href="../../../../../../_/images/fav/favicon-16x16.png">
<link rel="manifest" href="../../../../../../_/images/fav/site.webmanifest">
<link rel="mask-icon" href="../../../../../../_/images/fav/safari-pinned-tab.svg" color="#5bbad5">
<meta name="msapplication-TileColor" content="#ffc40d">
<meta name="theme-color" content="#ffffff">
<link href="../../../../../../_/css/font-open-sans.css" rel="stylesheet">
<!--
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.
-->
</head>
<body>
<div class="title-bar" data-responsive-toggle="responsive-menu" data-hide-for="medium">
<button type="button" data-toggle="responsive-menu"><i style='font-size: 32px; color: #fff; padding: 8px' class='fa fa-bars'></i></button>
<div class="title-bar-title">Apache NetBeans</div>
</div>
<div class="top-bar" id="responsive-menu">
<div class='top-bar-left'>
<a class='title' href="../../../../../../index.html"><img src='../../../../../../_/images/apache-netbeans.svg' style='padding: 8px; height: 48px;'> Apache NetBeans</a>
</div>
<div class="top-bar-right">
<ul class="vertical medium-horizontal menu" data-responsive-menu="drilldown medium-dropdown">
<li> <input id="search-input" type="text" placeholder="Search the docs"> </li>
<li> <a href="../../../../../../front/main/community">Community</a> </li>
<li> <a href="../../../../../../front/main/participate">Participate</a> </li>
<li> <a href="../../../../../../front/main/blogs">Blog</a></li>
<li> <a href="../../../../../../front/main/help">Get Help</a> </li>
<li> <a href="https://plugins.netbeans.apache.org/">Plugins</a> </li>
<li> <a href="../../../../../../front/main/download">Download</a> </li>
</ul>
</div>
</div>
<!-- src/templates/news -->
<section class="hero news alternate">
<div class='grid-container'>
<div class='cell'>
<div class="annotation">Latest release</div>
<h1>Apache NetBeans 28</h1>
<p><a class="button success" href="../../../../../../front/main/download/nb28">Download</a></p>
</div>
</div>
</section>
<div class='grid-container main-content tutorial'>
<article class="doc">
<h1 class="sect0">Using the Embedded EJB Container to Test Enterprise Applications</h1>
<div class="sectionbody">
<div class="admonitionblock note">
<table>
<tbody><tr>
<td class="icon"><i class="fa icon-note" title="Note"></i></td>
<td class="content">This tutorial needs a review.
You can <a href="https://github.com/apache/netbeans-antora-tutorials/edit/main/modules/ROOT/pages/kb/docs/javaee/javaee-entapp-junit.adoc" title="Edit this tutorial in github">edit it in GitHub </a>
following these <a href="../../../../../../tutorial/main/kb/docs/contributing">contribution guidelines.</a></td>
</tr></tbody>
</table>
</div>
</div>
<div id="toc" class="toc">
<div id="toctitle"></div>
<ul class="sectlevel1">
<li><a href="#_testing_a_session_bean">Testing a Session Bean</a>
<ul class="sectlevel2">
<li><a href="#_creating_the_project">Creating the Project</a></li>
<li><a href="#_creating_the_session_bean">Creating the Session Bean</a></li>
<li><a href="#_testing_the_session_bean">Testing the Session Bean</a></li>
<li><a href="#_modifying_the_test_to_specify_container_properties">Modifying the Test to Specify Container Properties</a></li>
<li><a href="#_using_beforeclass_and_afterclass_annotations">Using <code>@BeforeClass</code> and <code>@AfterClass</code> Annotations</a></li>
</ul>
</li>
<li><a href="#_testing_an_entity_class">Testing an Entity Class</a>
<ul class="sectlevel2">
<li><a href="#_creating_the_entity_class">Creating the Entity Class</a></li>
<li><a href="#_modifying_the_session_bean">Modifying the Session Bean</a></li>
<li><a href="#_testing_the_entity_class">Testing the Entity Class</a></li>
</ul>
</li>
<li><a href="#_downloading_the_solution_project">Downloading the Solution Project</a></li>
<li><a href="#_see_also">See Also</a></li>
</ul>
</div>
<div id="preamble">
<div class="sectionbody">
<div class="paragraph">
<p>This tutorial demonstrates how to create and run JUnit tests for a Java EE enterprise application. In this tutorial you will create a web application with an entity class and a session bean. You will first create a JUnit test class for the session bean and run the test in the embedded EJB container. You will then add an entity class to the project and modify the test class to add a test method for the entity class.</p>
</div>
<div class="paragraph">
<p><strong>Tutorial Exercises</strong></p>
</div>
<div class="ulist">
<ul>
<li>
<p><a href="#Exercise_1">Testing a Session Bean</a></p>
</li>
<li>
<p><a href="#Exercise_1a">Creating the Project</a></p>
</li>
<li>
<p><a href="#Exercise_1b">Creating the Session Bean</a></p>
</li>
<li>
<p><a href="#Exercise_1c">Testing the Session Bean</a></p>
</li>
<li>
<p><a href="#Exercise_1d">Modifying the Test to Specify Container Properties</a></p>
</li>
<li>
<p><a href="#Exercise_1e">Using @BeforeClass and @AfterClass Annotations</a></p>
</li>
<li>
<p><a href="#Exercise_2">Testing an Entity Class</a></p>
</li>
<li>
<p><a href="#Exercise_2a">Creating the Entity Class</a></p>
</li>
<li>
<p><a href="#Exercise_2b">Modifying the Session Bean</a></p>
</li>
<li>
<p><a href="#Exercise_2c">Testing the Entity Class</a></p>
</li>
<li>
<p><a href="#Exercise_3">Downloading the Solution Project</a></p>
</li>
</ul>
</div>
<div class="paragraph">
<p><strong>To follow this tutorial, you need the following software and resources.</strong></p>
</div>
<table class="tableblock frame-all grid-all stretch">
<colgroup>
<col style="width: 50%;">
<col style="width: 50%;">
</colgroup>
<thead>
<tr>
<th class="tableblock halign-left valign-top">Software or Resource</th>
<th class="tableblock halign-left valign-top">Version Required</th>
</tr>
</thead>
<tbody>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock"><a href="../../../../../../front/main/download/" class="xref page">NetBeans IDE</a></p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">7.2, 7.3, 7.4, 8.0, Java EE bundle</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock"><a href="http://www.oracle.com/technetwork/java/javase/downloads/index.html">Java Development Kit (JDK)</a></p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">version 7 or 8</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">GlassFish Server Open Source Edition</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">3.1.x or 4.x</p></td>
</tr>
</tbody>
</table>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
This tutorial requires the JUnit plugin. If you did not install the JUnit plugin when you installed the IDE, open the Plugins manager, select the Available plugins tab and install the JUnit plugin.
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p><strong>Prerequisites</strong></p>
</div>
<div class="paragraph">
<p>This document assumes you have some basic knowledge of, or programming experience with, the following technologies:</p>
</div>
<div class="ulist">
<ul>
<li>
<p>Java Programming</p>
</li>
<li>
<p>NetBeans IDE</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>Before starting this tutorial you may want to familiarize yourself with the following documents.</p>
</div>
<div class="ulist">
<ul>
<li>
<p><a href="../javaee-gettingstarted/" class="xref page">Getting Started with Java EE Applications</a></p>
</li>
<li>
<p><a href="../../java/junit-intro/" class="xref page">Writing JUnit Tests in NetBeans IDE</a></p>
</li>
<li>
<p><a href="http://download.oracle.com/docs/cd/E19798-01/821-1754/gjlde/index.html">Using the EJB 3.1 Embeddable API with Embedded GlassFish Server</a></p>
</li>
</ul>
</div>
<div class="paragraph">
<p>You can download <a href="https://netbeans.org/projects/samples/downloads/download/Samples%252FJavaEE%252FWebAppJUnit.zip">a zip archive of the finished project</a>.</p>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_testing_a_session_bean"><a class="anchor" href="#_testing_a_session_bean"></a>Testing a Session Bean</h2>
<div class="sectionbody">
<div class="paragraph">
<p>In this section you will create a simple Java EE web application that will contain a session bean and an entity class.</p>
</div>
<div class="sect2">
<h3 id="_creating_the_project"><a class="anchor" href="#_creating_the_project"></a>Creating the Project</h3>
<div class="olist arabic">
<ol class="arabic">
<li>
<p>Choose File &gt; New Project (Ctrl-Shift-N; ⌘-Shift-N on Mac) from the main menu.</p>
</li>
<li>
<p>Select Web Application from the Java Web category. Click Next.</p>
</li>
<li>
<p>Name the project <strong>WebAppJUnit</strong> and set the project location.</p>
</li>
<li>
<p>Deselect the Use Dedicated Folder option, if selected.
Click Next.</p>
<div class="olist arabic">
<ol class="arabic">
<li>
<p>Set the server to <strong>GlassFish Server</strong> and set the Java EE Version to <strong>Java EE 6 Web</strong> or <strong>Java EE 7 Web</strong>.
Click Finish.</p>
</li>
</ol>
</div>
</li>
</ol>
</div>
</div>
<div class="sect2">
<h3 id="_creating_the_session_bean"><a class="anchor" href="#_creating_the_session_bean"></a>Creating the Session Bean</h3>
<div class="paragraph">
<p>In this exercise you will create a very simple session bean that contains one method that adds two numbers.</p>
</div>
<div class="olist arabic">
<ol class="arabic">
<li>
<p>Right-click the WebAppJUnit project in the Projects window and choose New &gt; Other.</p>
</li>
<li>
<p>Select Session Bean in the Enterprise JavaBeans category. Click Next.</p>
</li>
<li>
<p>Type <strong>MyBean</strong> as the EJB Name.</p>
</li>
<li>
<p>Type <strong>bean</strong> for the Package name.</p>
</li>
<li>
<p>Select Stateless as the Session Type. Click Finish.</p>
</li>
</ol>
</div>
<div class="paragraph">
<p>When you click Finish, the new class opens in the editor.</p>
</div>
<div class="olist arabic">
<ol class="arabic">
<li>
<p>In the editor, add the following method <code>addNumbers</code> to the class.</p>
</li>
</ol>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">@Stateless
public class MyBean {
*public int addNumbers(int numberA, int numberB) {
return numberA + numberB;
}*
}</code></pre>
</div>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
It is not necessary to add an <code>@LocalBean</code> annotation or implement an interface in this tutorial. By default the bean exposes a no-interface view when no view is explicitly specified.
</td>
</tr>
</table>
</div>
<div class="olist arabic">
<ol class="arabic">
<li>
<p>Save your changes.</p>
</li>
</ol>
</div>
</div>
<div class="sect2">
<h3 id="_testing_the_session_bean"><a class="anchor" href="#_testing_the_session_bean"></a>Testing the Session Bean</h3>
<div class="paragraph">
<p>In this exercise you will create a test class for the session bean that will test the <code>addNumbers</code> method. The IDE can generate the new test class and skeleton test methods based on the methods in the target class.</p>
</div>
<div class="olist arabic">
<ol class="arabic">
<li>
<p>Right-click the <code>MyBean</code> class in the Projects window and choose Tools &gt; Create Tests.</p>
</li>
<li>
<p>Select JUnit in the Frameworks dropdown list.</p>
</li>
<li>
<p>Use the default values in the Create Tests dialog box. Click OK.</p>
</li>
</ol>
</div>
<div class="imageblock">
<div class="content">
<img src="../../../../_images/kb/docs/javaee/create-tests-dialog.png" alt="create tests dialog">
</div>
<div class="title">Figure 1. Create Tests dialog</div>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
The first time that you create a JUnit unit test you need to specify the JUnit version. Select JUnit 4.x in the Select JUnit Version dialog box and click Select.
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>When you click OK, the IDE generates the <code>MyBeanTest.java</code> file and opens the class in the editor.</p>
</div>
<div class="paragraph">
<p>In the Projects window you can see that the IDE generated the test class under the Test Packages node. By default, the IDE generates a skeleton test method in the test class that calls <code>javax.ejb.embeddable.EJBContainer.createEJBContainer()</code> to create an EJB container instance. The <code>createEJBContainer()</code> method is one of the methods in the <a href="http://download.oracle.com/javaee/6/api/javax/ejb/embeddable/EJBContainer.html">+ <code>EJBContainer</code> +</a> class that is part of the EJB 3.1 Embeddable API.</p>
</div>
<div class="paragraph">
<p>If you expand the Test Libraries node in the Projects window, you can see that the IDE automatically added GlassFish Server (embeddable container) and JUnit 4.x as test libraries. If you expand the GlassFish Server library, you can see that the library contains the <code>glassfish-embedded-static-shell.jar</code> .</p>
</div>
<div class="imageblock">
<div class="content">
<img src="../../../../_images/kb/docs/javaee/embedded-static-shell-jar.png" alt="embedded static shell jar">
</div>
<div class="title">Figure 2. Structure of project in the Projects window</div>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
The <code>glassfish-embedded-static-shell.jar</code> JAR does not contain the sources for the embedded EJB container. The <code>glassfish-embedded-static-shell.jar</code> JAR requires a local installation of GlassFish. The classpath for the local GlassFish installation is determined by the target server for the project. You can change the target server in the project&#8217;s Properties dialog box.
</td>
</tr>
</table>
</div>
<div class="olist arabic">
<ol class="arabic">
<li>
<p>Modify the generated skeleton test method to specify values for <code>numberA</code> , <code>numberB</code> and <code>expResult</code> and remove the default call to fail.</p>
</li>
</ol>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">@Test
public void testAddNumbers() throws Exception {
System.out.println("addNumbers");
*int numberA = 1;
int numberB = 2;*
EJBContainer container = javax.ejb.embeddable.EJBContainer.createEJBContainer();
MyBean instance = (MyBean)container.getContext().lookup("java:global/classes/MyBean");
*int expResult = 3;*
int result = instance.addNumbers(numberA, numberB);
assertEquals(expResult, result);
container.close();
}</code></pre>
</div>
</div>
<div class="olist arabic">
<ol class="arabic">
<li>
<p>Right-click the project in the Projects window and choose Test.</p>
</li>
</ol>
</div>
<div class="paragraph">
<p>When you run the test, the Test Results window opens in the IDE and displays the progress and results of the test.</p>
</div>
<div class="imageblock">
<div class="content">
<img src="../../../../_images/kb/docs/javaee/test-results1.png" alt="test results1">
</div>
<div class="title">Figure 3. Test Results window</div>
</div>
<div class="paragraph">
<p>You will see output similar to the following in the Output window.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">Testsuite: bean.MyBeanTest
addNumbers
...
Tests run: 1, Failures: 0, Errors: 0, Time elapsed: 31.272 sec
------------- Standard Output ---------------
addNumbers
...
------------- ---------------- ---------------
test-report:
test:
BUILD SUCCESSFUL (total time: 35 seconds)</code></pre>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_modifying_the_test_to_specify_container_properties"><a class="anchor" href="#_modifying_the_test_to_specify_container_properties"></a>Modifying the Test to Specify Container Properties</h3>
<div class="paragraph">
<p>When you used the Create Tests wizard, the IDE generated a default skeleton test class that contained code for starting the EJB container. In this exercise you will modify the generated code that starts the container to enable you to specify additional properties for the embedded container instance.</p>
</div>
<div class="olist arabic">
<ol class="arabic">
<li>
<p>Add the following code (in bold) to the test class.</p>
</li>
</ol>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">@Test
public void testAddNumbers() throws Exception {
System.out.println("addNumbers");
int numberA = 1;
int numberB = 2;
// Create a properties map to pass to the embeddable container:
*Map&lt;String, Object&gt; properties = new HashMap&lt;String, Object&gt;();*
// Use the MODULES property to specify the set of modules to be initialized,
// in this case a java.io.File
*properties.put(EJBContainer.MODULES, new File("build/jar"));*
// Create the container instance, passing it the properties map:
EJBContainer container = javax.ejb.embeddable.EJBContainer.createEJBContainer(*properties*);
// Create the instance using the container context to look up the bean
// in the directory that contains the built classes
MyBean instance = (MyBean) container.getContext().lookup("java:global/classes/MyBean");
int expResult = 3;
// Invoke the addNumbers method on the bean instance:
int result = instance.addNumbers(numberA, numberB);
assertEquals(expResult, result);
// Close the embeddable container:
container.close();
}</code></pre>
</div>
</div>
<div class="olist arabic">
<ol class="arabic">
<li>
<p>Right-click in the editor and choose Fix Imports (Alt-Shift-I; ⌘-Shift-I on Mac) to add import statements for <code>java.util.HashMap</code> and <code>java.util.Map</code> .</p>
</li>
<li>
<p>Run the test again to confirm that the modified test works and that the container is created correctly.</p>
</li>
</ol>
</div>
<div class="paragraph">
<p>You can click the Rerun button in the Test Results window.</p>
</div>
</div>
<div class="sect2">
<h3 id="_using_beforeclass_and_afterclass_annotations"><a class="anchor" href="#_using_beforeclass_and_afterclass_annotations"></a>Using <code>@BeforeClass</code> and <code>@AfterClass</code> Annotations</h3>
<div class="paragraph">
<p>In this exercise you will modify the test class to create individual methods for creating and shutting down the container instance. This can be useful when you want to run several tests that can use the same container instance. In this way you do not need to open and close a container instance for each test, and instead create one instance that is created before the tests are run and is then closed after all the tests are completed.</p>
</div>
<div class="paragraph">
<p>In this exercise you will move the code that creates the EJB container to the <code>setUpClass</code> method. The <code>setUpClass</code> method is annotated with <code>@BeforeClass</code> that is used to indicate a method that will be run first, before the other methods in the test class. In this example, the container instance will be created before the <code>testAddNumbers</code> test method and the container will exist until it is shut down.</p>
</div>
<div class="paragraph">
<p>Similarly, you will move the code that shuts down the container to the <code>tearDownClass</code> method that is annotated with <code>@AfterClass</code> .</p>
</div>
<div class="olist arabic">
<ol class="arabic">
<li>
<p>Add the following field to the test class.</p>
</li>
</ol>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">private static EJBContainer container;</code></pre>
</div>
</div>
<div class="olist arabic">
<ol class="arabic">
<li>
<p>Copy the code that creates the container from the <code>testAddNumbers</code> test method to the <code>setUpClass</code> method and</p>
</li>
</ol>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">@BeforeClass
public static void setUpClass() *throws Exception* {
*Map&lt;String, Object&gt; properties = new HashMap&lt;String, Object&gt;();
properties.put(EJBContainer.MODULES, new File("build/jar"));
container = EJBContainer.createEJBContainer(properties);
System.out.println("Opening the container");*
}</code></pre>
</div>
</div>
<div class="olist arabic">
<ol class="arabic">
<li>
<p>Copy the code that closes the container from the <code>testAddNumbers</code> test method to the <code>tearDownClass</code> method.</p>
</li>
</ol>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">@AfterClass
public static void tearDownClass() *throws Exception* {
*container.close();
System.out.println("Closing the container");*
}</code></pre>
</div>
</div>
<div class="olist arabic">
<ol class="arabic">
<li>
<p>Remove the redundant code from the <code>testAddNumbers</code> method. Save your changes.</p>
</li>
</ol>
</div>
<div class="paragraph">
<p>The test class should now look like the following.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">public class MyBeanTest {
private static EJBContainer container;
public MyBeanTest() {
}
@BeforeClass
public static void setUpClass() throws Exception {
Map&lt;String, Object&gt; properties = new HashMap&lt;String, Object&gt;();
properties.put(EJBContainer.MODULES, new File("build/jar"));
container = EJBContainer.createEJBContainer(properties);
System.out.println("Opening the container");
}
@AfterClass
public static void tearDownClass() throws Exception {
container.close();
System.out.println("Closing the container");
}
@Before
public void setUp() {
}
@After
public void tearDown() {
}
/**
* Test of addNumbers method, of class MyBean.
*/
@Test
public void testAddNumbers() throws Exception {
System.out.println("addNumbers");
int numberA = 1;
int numberB = 2;
// Create the instance using the container context to look up the bean
// in the directory that contains the built classes
MyBean instance = (MyBean) container.getContext().lookup("java:global/classes/MyBean");
int expResult = 3;
// Invoke the addNumbers method on the bean instance:
int result = instance.addNumbers(numberA, numberB);
assertEquals(expResult, result);
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>If you run the test again to confirm that the container is created and shut down correctly, you will see output similar to the following in the Test Results window.</p>
</div>
<div class="imageblock">
<div class="content">
<img src="../../../../_images/kb/docs/javaee/test-results2a.png" alt="test results2a">
</div>
<div class="title">Figure 4. Test Results window</div>
</div>
<div class="paragraph">
<p>You can see that the <code>setUpClass</code> method ran before the <code>addNumbers</code> test and printed "Opening the container".</p>
</div>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_testing_an_entity_class"><a class="anchor" href="#_testing_an_entity_class"></a>Testing an Entity Class</h2>
<div class="sectionbody">
<div class="paragraph">
<p>In this section you will create an entity class and persistence unit and modify the session bean to inject the entity manager and access the entities. You will add a simple method to the new entity class that prints the id number of the entry to the output. You will then add some simple methods to the session bean to create and verify entries in the database.</p>
</div>
<div class="sect2">
<h3 id="_creating_the_entity_class"><a class="anchor" href="#_creating_the_entity_class"></a>Creating the Entity Class</h3>
<div class="paragraph">
<p>In this section you will use the New Entity Class wizard to create an entity class and persistence unit with the database connection details.</p>
</div>
<div class="olist arabic">
<ol class="arabic">
<li>
<p>Right-click the WebAppJUnit project in the Projects window and choose New &gt; Other.</p>
</li>
<li>
<p>Select Entity Class in the Persistence category. Click Next.</p>
</li>
<li>
<p>Type <strong>SimpleEntity</strong> as the Class Name.</p>
</li>
<li>
<p>Select bean from the Package dropdown list.</p>
</li>
<li>
<p>Type <strong>int</strong> as the Primary Key Type. Click Next.</p>
</li>
<li>
<p>Use the default Persistence Unit Name and Persistence Provider.</p>
</li>
<li>
<p>Select <code>jdbc/sample</code> as the data source and Drop and Create as the strategy. Click Finish.</p>
</li>
</ol>
</div>
<div class="imageblock">
<div class="content">
<img src="../../../../_images/kb/docs/javaee/create-entity-wizard.png" alt="create entity wizard">
</div>
<div class="title">Figure 5. Create Entity Class dialog</div>
</div>
<div class="paragraph">
<p>When you click Finish, the new entity class opens in the editor. If you expand the Configuration Files node in the Projects window, you can see that the IDE automatically generated the <code>persistence.xml</code> file that defines the properties of the persistence unit <code>WebAppJUnitPU</code> .</p>
</div>
<div class="olist arabic">
<ol class="arabic">
<li>
<p>In the editor, add the following private field to the entity class.</p>
</li>
</ol>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">private String name;</code></pre>
</div>
</div>
<div class="olist arabic">
<ol class="arabic">
<li>
<p>Right-click in the Source Editor and choose Insert Code (Alt-Insert; Ctrl-I on Mac) and select Getter and Setter to open the Generate Getters and Setters dialog box.</p>
</li>
<li>
<p>Select the <code>name</code> field in the dialog box. Click Generate.</p>
</li>
<li>
<p>Add the following method to the class.</p>
</li>
</ol>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">public SimpleEntity(int id) {
this.id = id;
name = "Entity number " + id + " created at " + new Date();
}</code></pre>
</div>
</div>
<div class="olist arabic">
<ol class="arabic">
<li>
<p>Use the <code>@NamedQueries</code> and <code>@NamedQuery</code> annotations to create a named SQL query.</p>
</li>
</ol>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">@Entity
*@NamedQueries({@NamedQuery(name = "SimpleEntity.findAll", query = "select e from SimpleEntity e")})*
public class SimpleEntity implements Serializable {</code></pre>
</div>
</div>
<div class="olist arabic">
<ol class="arabic">
<li>
<p>Create a default constructor.</p>
</li>
</ol>
</div>
<div class="paragraph">
<p>You can click the suggestion icon that is displayed in the gutter next to the class declaration if you want the IDE to generate the constructor for you.</p>
</div>
<div class="olist arabic">
<ol class="arabic">
<li>
<p>Fix your imports to add import statements for <code>javax.persistence.NamedQueries</code> , <code>javax.persistence.NamedQuery</code> and <code>java.util.Date</code> . Save your changes.</p>
</li>
</ol>
</div>
<div class="paragraph">
<p>In addition to the default generated code, the entity class should now look similar to the following:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">package bean;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
@Entity
@NamedQueries({@NamedQuery(name = "SimpleEntity.findAll", query = "select e from SimpleEntity e")})
public class SimpleEntity implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
private String name;
public SimpleEntity() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public SimpleEntity(int id) {
this.id = id;
name = "Entity number " + id + " created at " + new Date();
}
...
}</code></pre>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_modifying_the_session_bean"><a class="anchor" href="#_modifying_the_session_bean"></a>Modifying the Session Bean</h3>
<div class="paragraph">
<p>In this exercise you will edit the <code>MyBean</code> session bean to add methods for inserting and retrieving data to the database table.</p>
</div>
<div class="olist arabic">
<ol class="arabic">
<li>
<p>Open <code>MyBean.java</code> in the editor.</p>
</li>
<li>
<p>Right-click in the editor and choose Insert Code (Alt-Insert; Ctrl-I on Mac) and choose Use Entity Manager from the popup menu.</p>
</li>
</ol>
</div>
<div class="paragraph">
<p>When you chose Use Entity Manager, the IDE added the following code to the class to inject the entity manager. You can see that the name of the persistence unit is generated automatically.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">@PersistenceContext(unitName="WebAppJUnitPU")
private EntityManager em;</code></pre>
</div>
</div>
<div class="olist arabic">
<ol class="arabic">
<li>
<p>Add the following <code>verify</code> and <code>insert</code> methods.</p>
</li>
</ol>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">@PermitAll
public int verify() {
String result = null;
Query q = em.createNamedQuery("SimpleEntity.findAll");
Collection entities = q.getResultList();
int s = entities.size();
for (Object o : entities) {
SimpleEntity se = (SimpleEntity)o;
System.out.println("Found: " + se.getName());
}
return s;
}
@PermitAll
public void insert(int num) {
for (int i = 1; i &lt;= num; i++) {
System.out.println("Inserting # " + i);
SimpleEntity e = new SimpleEntity(i);
em.persist(e);
}
}</code></pre>
</div>
</div>
<div class="olist arabic">
<ol class="arabic">
<li>
<p>Fix your imports to import <code>javax.persistence.Query</code> and save your changes.</p>
</li>
</ol>
</div>
</div>
<div class="sect2">
<h3 id="_testing_the_entity_class"><a class="anchor" href="#_testing_the_entity_class"></a>Testing the Entity Class</h3>
<div class="paragraph">
<p>In this exercise you will edit the test class to add a method to test that the application is able to look up the EJB and that the <code>insert</code> and <code>verify</code> methods are behaving correctly.</p>
</div>
<div class="olist arabic">
<ol class="arabic">
<li>
<p>Start the JavaDB database.</p>
</li>
<li>
<p>Open the <code>MyBeanTest.java</code> test class in the editor.</p>
</li>
<li>
<p>Edit the test class to add the following <code>testInsert</code> test method.</p>
</li>
</ol>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">@Test
public void testInsert() throws Exception {
// Lookup the EJB
System.out.println("Looking up EJB...");
MyBean instance = (MyBean) container.getContext().lookup("java:global/classes/MyBean");
System.out.println("Inserting entities...");
instance.insert(5);
int res = instance.verify();
System.out.println("JPA call returned: " + res);
System.out.println("Done calling EJB");
Assert.assertTrue("Unexpected number of entities", (res == 5));
System.out.println("..........SUCCESSFULLY finished embedded test");
}</code></pre>
</div>
</div>
<div class="olist arabic">
<ol class="arabic">
<li>
<p>Right-click the project node in the Projects window and choose Test from the popup menu.</p>
</li>
</ol>
</div>
<div class="paragraph">
<p>The Test Results window will open and display output that is similar to the following.</p>
</div>
<div class="imageblock">
<div class="content">
<img src="../../../../_images/kb/docs/javaee/test-results2b.png" alt="test results2b">
</div>
<div class="title">Figure 6. Test Results window after adding testInsert test</div>
</div>
<div class="paragraph">
<p>You can see the progress of the tests and the order in which the tests were run from the print messages that were added to the test class.</p>
</div>
<div class="paragraph">
<p>Now that you have a test for your session bean and know that your entity class connection works, you can start coding a web interface for the application.</p>
</div>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_downloading_the_solution_project"><a class="anchor" href="#_downloading_the_solution_project"></a>Downloading the Solution Project</h2>
<div class="sectionbody">
<div class="paragraph">
<p>You can download the solution to this tutorial as a project in the following ways.</p>
</div>
<div class="ulist">
<ul>
<li>
<p>Download <a href="https://netbeans.org/projects/samples/downloads/download/Samples%252FJavaEE%252FWebAppJUnit.zip">a zip archive of the finished project</a>.</p>
</li>
<li>
<p>Checkout the project sources from the NetBeans Samples by performing the following steps:</p>
<div class="olist arabic">
<ol class="arabic">
<li>
<p>Choose Team &gt; Subversion &gt; Checkout from the main menu.</p>
</li>
<li>
<p>In the Checkout dialog box, enter the following Repository URL:
<code><a href="https://svn.netbeans.org/svn/samples~samples-source-code" class="bare">https://svn.netbeans.org/svn/samples~samples-source-code</a></code>
Click Next.</p>
<div class="olist arabic">
<ol class="arabic">
<li>
<p>Click Browse to open the Browse Repository Folders dialog box.</p>
</li>
<li>
<p>Expand the root node and select <strong>samples/javaee/WebAppJUnit</strong>. Click OK.</p>
</li>
<li>
<p>Specify the Local Folder for the sources (the local folder must be empty).</p>
</li>
<li>
<p>Click Finish.</p>
</li>
</ol>
</div>
</li>
</ol>
</div>
</li>
</ul>
</div>
<div class="paragraph">
<p>When you click Finish, the IDE initializes the local folder as a Subversion repository and checks out the project sources.</p>
</div>
<div class="olist arabic">
<ol class="arabic">
<li>
<p>Click Open Project in the dialog that appears when checkout is complete.</p>
</li>
</ol>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
You need a Subversion client to checkout the sources. For more about installing Subversion, see the section on <a href="../../ide/subversion/#settingUp" class="xref page">Setting up Subversion</a> in the <a href="../../ide/subversion/" class="xref page">Guide to Subversion in NetBeans IDE</a>.
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p><a href="../../../../../../front/main/community/mailing-lists/" class="xref page">Send Feedback on This Tutorial</a></p>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_see_also"><a class="anchor" href="#_see_also"></a>See Also</h2>
<div class="sectionbody">
<div class="paragraph">
<p>For more information about using NetBeans IDE to develop Java EE applications, see the following resources:</p>
</div>
<div class="ulist">
<ul>
<li>
<p><a href="../javaee-intro/" class="xref page">Introduction to Java EE Technology</a></p>
</li>
<li>
<p><a href="../javaee-gettingstarted/" class="xref page">Getting Started with Java EE Applications</a></p>
</li>
<li>
<p><a href="../../web/quickstart-webapps/" class="xref page">Introduction to Developing Web Applications</a></p>
</li>
<li>
<p><a href="../../java-ee/" class="xref page">Java EE &amp;amp; Java Web Learning Trail</a></p>
</li>
</ul>
</div>
<div class="paragraph">
<p>You can find more information about using EJB 3.1 Enterprise Beans in the <a href="http://download.oracle.com/javaee/6/tutorial/doc/">Java EE 6 Tutorial</a>.</p>
</div>
<div class="paragraph">
<p>To send comments and suggestions, get support, and keep informed on the latest developments on the NetBeans IDE Java EE development features, <a href="../../../../../../front/main/community/mailing-lists/" class="xref page">join the nbj2ee mailing list</a>.</p>
</div>
</div>
</div>
<section class='tools'>
<ul class="menu align-center">
<li><a title="Facebook" href="https://www.facebook.com/NetBeans"><i class="fa fa-md fa-facebook"></i></a></li>
<li><a title="Twitter" href="https://twitter.com/netbeans"><i class="fa fa-md fa-twitter"></i></a></li>
<li><a title="Github" href="https://github.com/apache/netbeans"><i class="fa fa-md fa-github"></i></a></li>
<li><a title="YouTube" href="https://www.youtube.com/user/netbeansvideos"><i class="fa fa-md fa-youtube"></i></a></li>
<li><a title="Atom Feed" href="https://netbeans.apache.org/blogs/atom"><i class="fa fa-mf fa-rss"></i></a></li>
<li><a title="Slack" href="https://tinyurl.com/netbeans-slack-signup/"><i class="fa fa-md fa-slack"></i></a></li>
<li><a title="Issues" href="https://github.com/apache/netbeans/issues"><i class="fa fa-mf fa-bug"></i></a></li>
</ul>
<ul class="menu align-center">
<li><a href="https://github.com/apache/netbeans-antora-tutorials/edit/main/modules/ROOT/pages/kb/docs/javaee/javaee-entapp-junit.adoc" title="See this page in github"><i class="fa fa-md fa-edit"></i> See this page in GitHub.</a></li>
</ul>
</section>
</article>
</div>
<div class='grid-container incubator-area' style='margin-top: 64px'>
<div class='grid-x grid-padding-x'>
<div class='large-auto cell text-center'>
<a href="https://www.apache.org/">
<img style="height: 60px" title="Apache Software Foundation" src="../../../../../../_/images/asf_logo_wide.svg" />
</a>
</div>
<div class='large-auto cell text-center'>
<a href="https://www.apache.org/events/current-event.html">
<img style="width:234px; height: 60px;" title="Apache Software Foundation current event" src="https://www.apache.org/events/current-event-234x60.png"/>
</a>
</div>
</div>
</div>
<footer>
<div class="grid-container">
<div class="grid-x grid-padding-x">
<div class="large-auto cell">
<h1><a href="../../../../../../front/main/about">About</a></h1>
<ul>
<li><a href="../../../../../../front/main/community/who">Who's Who</a></li>
<li><a href="https://www.apache.org/foundation/thanks.html">Thanks</a></li>
<li><a href="https://www.apache.org/foundation/sponsorship.html">Sponsorship</a></li>
<li><a href="https://www.apache.org/security/">Security</a></li>
</ul>
</div>
<div class="large-auto cell">
<h1><a href="../../../../../../front/main/community">Community</a></h1>
<ul>
<li><a href="../../../../../../front/main/community/mailing-lists">Mailing lists</a></li>
<li><a href="../../../../../../front/main/community/committer">Becoming a committer</a></li>
<li><a href="../../../../../../front/main/community/events">NetBeans Events</a></li>
<li><a href="https://www.apache.org/events/current-event.html">Apache Events</a></li>
</ul>
</div>
<div class="large-auto cell">
<h1><a href="../../../../../../front/main/participate">Participate</a></h1>
<ul>
<li><a href="../../../../../../front/main/participate/submit-pr">Submitting Pull Requests</a></li>
<li><a href="../../../../../../front/main/participate/report-issue">Reporting Issues</a></li>
<li><a href="../../../../../../front/main/participate/#documentation">Improving the documentation</a></li>
</ul>
</div>
<div class="large-auto cell">
<h1><a href="../../../../../../front/main/help">Get Help</a></h1>
<ul>
<li><a href="../../../../../../front/main/help/#documentation">Documentation</a></li>
<li><a href="../../../../../../wiki/main/wiki">Wiki</a></li>
<li><a href="../../../../../../front/main/help/#support">Community Support</a></li>
<li><a href="../../../../../../front/main/help/commercial-support">Commercial Support</a></li>
</ul>
</div>
<div class="large-auto cell">
<h1><a href="../../../../../../front/main/download">Download</a></h1>
<ul>
<li><a href="../../../../../../front/main/download">Releases</a></li>
<li><a href="https://plugins.netbeans.apache.org/">Plugins</a></li>
<li><a href="../../../../../../front/main/download/#_daily_builds_and_building_from_source">Building from source</a></li>
<li><a href="../../../../../../front/main/download/#_older_releases">Previous releases</a></li>
</ul>
</div>
</div>
</div>
</footer>
<div class='footer-disclaimer'>
<div class="footer-disclaimer-content">
<p>Copyright &copy; 2017-2025 <a href="https://www.apache.org">The Apache Software Foundation</a>.</p>
<p>Licensed under the Apache <a href="https://www.apache.org/licenses/">license</a>, version 2.0</p>
<div style='max-width: 40em; margin: 0 auto'>
<p>Apache, Apache NetBeans, NetBeans, the Apache feather logo and the Apache NetBeans logo are trademarks of <a href="https://www.apache.org">The Apache Software Foundation</a>.</p>
<p>Oracle and Java are registered trademarks of Oracle and/or its affiliates.</p>
<p>The Apache NetBeans website conforms to the <a href="https://privacy.apache.org/policies/privacy-policy-public.html">Apache Software Foundation Privacy Policy</a></p>
</div>
</div>
</div>
<script src="../../../../../../_/js/vendor/lunr.js"></script>
<script src="../../../../../../_/js/search-ui.js" id="search-ui-script" data-site-root-path="../../../../../.." data-snippet-length="100" data-stylesheet="../../../../../../_/css/search.css"></script>
<script async src="../../../../../../search-index.js"></script>
<script src="../../../../../../_/js/vendor/jquery.min.js"></script>
<script src="../../../../../../_/js/vendor/what-input.min.js"></script>
<script src="../../../../../../_/js/vendor/foundation.min.js"></script>
<script src="../../../../../../_/js/vendor/jquery.colorbox-min.js"></script>
<script src="../../../../../../_/js/netbeans.js"></script>
<script>
$(function(){ $(document).foundation(); });
</script>
<script src="../../../../../../_/js/vendor/highlight.min.js"></script>
<script>
document.addEventListener('DOMContentLoaded', (event) => {
document.querySelectorAll('pre code').forEach((el) => {
hljs.highlightElement(el);
});
});
</script>
</body>
</html>