How do I start unit testing a Java EE JAX-RS application using the built-in GlassFish and Java DB / Derby, ideally in NetBeans sans Maven?

I am relatively new to JAX-RS, JPA, GlassFish, Java DB and NetBeans, and I would like to write unit tests for my code. [Version numbers below.] However, I was stuck on where to start. I did a bit of work, but I don’t have a clear idea of ​​how to set up the built-in test of my code yet. I use NetBeans, but my question is general. I would like to formulate my question more clearly, but this is the best I could do. So far, I have found the following possible parts (more like hints at this point).

o I want to install this without Maven, but that means I have to install the built-in banks manually. Q: Where can I find them?

o Create versions of my xml configuration files (glassfish-resources.xml and persistence.xml) that specify the embedded versions of GlassFish and Java DB. Q: But how do you tell NetBeans to use them for testing, and not for production ones that rely on their installed version?

I think persistence.xml would look something like this (from using hibernate with a built-in derby ):

<property name="javax.persistence.jdbc.driver" value="org.apache.derby.jdbc.EmbeddedDriver"/> <property name="javax.persistence.jdbc.url" value="jdbc:derby:test"/> <property name="javax.persistence.jdbc.user" value="root"/> <property name="javax.persistence.jdbc.password" value="root"/> 

o Create a custom Glassfish domain configuration file ( Embedded GlassFish ignores Maven test resources ). Question: What should it look like? I have domain.xml from the default domain1 that was created with my NetBeans installation, but there are a lot of things.

o As soon as my project gets access to embedded files and it is configured to use them, what does my JUnit look like? http://jersey.java.net/nonav/documentation/latest/client-api.html#d4e759 says:

 protected void setUp() throws Exception { ... glassfish = new GlassFish(BASE_URI.getPort()); ScatteredWar war = new ScatteredWar(...); glassfish.deploy(war); ... 

However, I also saw that EJBContainer mentioned, for example, (from http://docs.oracle.com/javaee/6/tutorial/doc/gkcqz.html ):

 @BeforeClass public static void initContainer() throws Exception { ec = EJBContainer.createEJBContainer(); ctx = ec.getContext(); } 

o I use JPA, so I need access to PersistenceContext / EntityManager. I am currently viewing it through:

 new InitialContext().lookup("java:module/<jax-rs resource name>"); 

But I also saw:

  emf = Persistence.createEntityManagerFactory("chapter02PU"); 

Q: What is the right way to get this?

I am very grateful for your help.

  • Versions:
    • GlassFish Server Open Source Edition 3.1.2 (Build 23)
    • Java DB / Derby: 10.8.1.2 - (1095077)
    • NetBeans IDE 7.1 (Build 201112071828)
+4
source share
2 answers

OK, I got the GlassFish infrastructure and was able to successfully create tests for a simple servlet and a simple JAX-RS service. It took some searching to figure this out, so I will share it here if others can use it. I have not yet delved into testing JPA, but one step at a time. I am new to StackOverflow, so I don’t know the accepted protocol for sharing a lot of code in the answer, but it says: How to download the built-in GlassFish instance, which serves for a simple servlet and JAX-RS resource, then tests them. Packets omitted. Inline javadocs: http://embedded-glassfish.java.net/nonav/apidocs/

1. Configure JAX-RS:

 package org.netbeans.rest.application.config; @javax.ws.rs.ApplicationPath("resources") public class ApplicationConfig extends javax.ws.rs.core.Application { } 

2. Define a resource: package rest;

 @Path("generic") public class GenericResource { public static final String MESSAGE = "hi there"; public GenericResource() { } @GET @Produces(MediaType.TEXT_PLAIN) public String sayHi() { return MESSAGE; } } 

3. Define the servlet:

 package servlet; @WebServlet(urlPatterns = {"/hello"}) public class HelloWebServlet extends HttpServlet { public HelloWebServlet() { } @Override public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException { PrintWriter pw = res.getWriter(); try { pw.println(GenericResource.MESSAGE); } catch (Exception ex) { e.printStackTrace(); } } } 

4. Define tests using the Jersey REST client, JUnit 4, http://download.java.net/maven/glassfish/org/glassfish/extras/glassfish-embedded-all/3.1.1/glassfish-embedded-all-3.1 .1.jar

 package rest; public class NewServletTest { private static final Logger LOG = Logger.getLogger(NewServletTest.class.getCanonicalName()); private static GlassFish glassfish = null; private static final String WEB_APP_NAME = "RestTemp"; private static final String BASE_URI = "http://localhost:" + 8080 + "/" + WEB_APP_NAME; private static final String REST_URI = BASE_URI + "/" + "resources" + "/" + "generic"; public NewServletTest() { } @BeforeClass public static void startServer() { try { GlassFishProperties gfProps = new GlassFishProperties(); gfProps.setPort("http-listener", 8080); // NB: not sure where name comes from - a standard property? glassfish = GlassFishRuntime.bootstrap().newGlassFish(gfProps); glassfish.start(); Deployer deployer = glassfish.getDeployer(); ScatteredArchive archive = new ScatteredArchive(WEB_APP_NAME, ScatteredArchive.Type.WAR); File buildDir = new File("build", "classes"); // NB: location depends on IDE setup archive.addClassPath(buildDir); deployer.deploy(archive.toURI()); } catch (GlassFishException ex) { LOG.log(Level.SEVERE, null, ex); } catch (IOException ex) { LOG.log(Level.SEVERE, null, ex); } } @AfterClass public static void shutDownServer() { if (glassfish != null) { try { glassfish.stop(); glassfish.dispose(); glassfish = null; } catch (GlassFishException ex) { LOG.log(Level.SEVERE, "tearDownClass(): exception: ", ex); } } } @Before public void setUp() { } @After public void tearDown() { } @Test public void testPing() throws MalformedURLException, IOException { URL url = new URL(BASE_URI + "/hello"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.connect(); InputStream inputStream = conn.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(inputStream)); assertEquals(GenericResource.MESSAGE, br.readLine()); } @Test public void testGet() { WebResource r = Client.create().resource(REST_URI); ClientResponse cr = r.accept(MediaType.TEXT_PLAIN).get(ClientResponse.class); // GET String crEntityStr = cr.getEntity(String.class); ClientResponse.Status crStatus = cr.getClientResponseStatus(); assertEquals(GenericResource.MESSAGE, crEntityStr); assertEquals(ClientResponse.Status.OK, crStatus); } } 

To create this project in NetBeans:

  • Choose New Project> Java Application. accept default values
  • remove JavaApplicationTemp
  • use NetBeans to create the above files in the IDE folder of the source packages (go to src /):
    • org.netbeans.rest.application.config.ApplicationConfig
    • rest.GenericResource
    • servlet.HelloWebServlet
  • Choose New> JUnit Test. select default values, select JUnit 4.x
  • remove NewEmptyJUnitTest
  • use NetBeans to create the above file in the IDE folder of the test packages (will go into test /):
    • rest.NewServletTest
  • edit the project property and add Glassfish-embedded-all-3.1.1.jar to the library> Compilation Category
  • Choose Run> Test Project. Ideally, you will see three tests passed!

Hope this helps!

+5
source

If you are using Netbeans, just install the JUnit plugin. After installation, create a package for storing test classes, right-click the newly created package and select "Create-> Other". A menu appears with all installed file types. Go to the JUnit package and select "JUnit Test" in the right pane.

This will create a piece of the JUnit class for you. From here, you just need to define a method for each test and annotate them using @Test.

I would suggest starting with one. After you have written a simple test, go to the "Run" menu at the top of the application and select "Test Project ([yourAppName]").

We hope that this will lead you to the right path.

0
source

Source: https://habr.com/ru/post/1399809/


All Articles