Rest Testing Amongst Arquillian Inward Jboss

This article volition explicate how nosotros tin automate REST spider web service testing using Arquillian too JBoss spider web server.

First, you lot must create a javaee6 nation of war (non-blank) projection from jboss-javaee6 archetype. This should create a projection alongside Member model, service, repository, controller too spider web service resource. The archetype volition likewise generate a exam representative for the controller alongside exam information rootage too persistence file.

In representative you lot don't conduct maintain the archetype, I'm writing the almost of import classes: Model
package com.broodcamp.jboss_javaee6_war.model;  import java.io.Serializable;  import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table; import javax.persistence.UniqueConstraint; import javax.validation.constraints.Digits; import javax.validation.constraints.NotNull; import javax.validation.constraints.Pattern; import javax.validation.constraints.Size; import javax.xml.bind.annotation.XmlRootElement;  import org.hibernate.validator.constraints.Email; import org.hibernate.validator.constraints.NotEmpty;  @SuppressWarnings("serial") @Entity @XmlRootElement @Table(uniqueConstraints = @UniqueConstraint(columnNames = "email")) populace class Member implements Serializable {      @Id     @GeneratedValue     private Long id;      @NotNull     @Size(min = 1, max = 25)     @Pattern(regexp = "[^0-9]*", message = "Must non comprise numbers")     private String name;      @NotNull     @NotEmpty     @Email     private String email;      @NotNull     @Size(min = 10, max = 12)     @Digits(fraction = 0, integer = 12)     @Column(name = "phone_number")     private String phoneNumber;      populace Long getId() {         render id;     }      populace void setId(Long id) {         this.id = id;     }      populace String getName() {         render name;     }      populace void setName(String name) {         this.name = name;     }      populace String getEmail() {         render email;     }      populace void setEmail(String email) {         this.email = email;     }      populace String getPhoneNumber() {         render phoneNumber;     }      populace void setPhoneNumber(String phoneNumber) {         this.phoneNumber = phoneNumber;     } } 
Web service resource:
package com.broodcamp.jboss_javaee6_war.rest;  import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.logging.Logger;  import javax.enterprise.context.RequestScoped; import javax.inject.Inject; import javax.persistence.NoResultException; import javax.validation.ConstraintViolation; import javax.validation.ConstraintViolationException; import javax.validation.ValidationException; import javax.validation.Validator; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response;  import com.broodcamp.jboss_javaee6_war.data.MemberRepository; import com.broodcamp.jboss_javaee6_war.model.Member; import com.broodcamp.jboss_javaee6_war.service.MemberRegistration;  /**  * JAX-RS Example  * <p/>  * This class produces a RESTful service to read/write the contents of the  * members table.  */ @RequestScoped populace class MemberResourceRESTService implements IMemberResourceRESTService {   @Inject  private Logger log;   @Inject  private Validator validator;   @Inject  private MemberRepository repository;   @Inject  MemberRegistration registration;   @GET  @Produces(MediaType.APPLICATION_JSON)  populace List<Member> listAllMembers() {   render repository.findAllOrderedByName();  }   @GET  @Path("/{id:[0-9][0-9]*}")  @Produces(MediaType.APPLICATION_JSON)  populace Member lookupMemberById(@PathParam("id") long id) {   Member fellow member = repository.findById(id);   if (member == null) {    throw novel WebApplicationException(Response.Status.NOT_FOUND);   }   render member;  }   /**   * Creates a novel fellow member from the values provided. Performs validation, too   * volition render a JAX-RS reply alongside either 200 ok, or alongside a map of   * fields, too related errors.   */  @Override  populace Response createMember(Member member) {    Response.ResponseBuilder builder = null;    essay {    // Validates fellow member using edible bean validation    validateMember(member);     registration.register(member);     // Create an "ok" reply    builder = Response.ok();   } select handgrip of (ConstraintViolationException ce) {    // Handle edible bean validation issues    builder = createViolationResponse(ce.getConstraintViolations());   } select handgrip of (ValidationException e) {    // Handle the unique constrain violation    Map<String, String> responseObj = novel HashMap<String, String>();    responseObj.put("email", "Email taken");    builder = Response.status(Response.Status.CONFLICT).entity(      responseObj);   } select handgrip of (Exception e) {    // Handle generic exceptions    Map<String, String> responseObj = novel HashMap<String, String>();    responseObj.put("error", e.getMessage());    builder = Response.status(Response.Status.BAD_REQUEST).entity(      responseObj);   }    render builder.build();  }   /**   * <p>   * Validates the given Member variable too throws validation exceptions   * based on the type of error. If the fault is criterion edible bean validation   * errors thence it volition throw a ConstraintValidationException alongside the laid of   * the constraints violated.   * </p>   * <p>   * If the fault is caused because an existing fellow member alongside the same electronic mail is   * registered it throws a regular validation exception thence that it tin last   * interpreted separately.   * </p>   *    * @param fellow member   *            Member to last validated   * @throws ConstraintViolationException   *             If Bean Validation errors be   * @throws ValidationException   *             If fellow member alongside the same electronic mail already exists   */  private void validateMember(Member member)    throws ConstraintViolationException, ValidationException {   // Create a edible bean validator too depository fiscal establishment agree for issues.   Set<ConstraintViolation<Member>> violations = validator     .validate(member);    if (!violations.isEmpty()) {    throw novel ConstraintViolationException(      novel HashSet<ConstraintViolation<?>>(violations));   }    // Check the uniqueness of the electronic mail address   if (emailAlreadyExists(member.getEmail())) {    throw novel ValidationException("Unique Email Violation");   }  }   /**   * Creates a JAX-RS "Bad Request" reply including a map of all violation   * fields, too their message. This tin thence last used yesteryear clients to present   * violations.   *    * @param violations   *            H5N1 laid of violations that needs to last reported   * @return JAX-RS reply containing all violations   */  private Response.ResponseBuilder createViolationResponse(    Set<ConstraintViolation<?>> violations) {   log.fine("Validation completed. violations found: " + violations.size());    Map<String, String> responseObj = novel HashMap<String, String>();    for (ConstraintViolation<?> violation : violations) {    responseObj.put(violation.getPropertyPath().toString(),      violation.getMessage());   }    render Response.status(Response.Status.BAD_REQUEST).entity(responseObj);  }   /**   * Checks if a fellow member alongside the same electronic mail address is already registered.   * This is the solely means to easily capture the   * "@UniqueConstraint(columnNames = "email")" constraint from the Member   * class.   *    * @param electronic mail   *            The electronic mail to depository fiscal establishment agree   * @return True if the electronic mail already exists, too imitation otherwise   */  populace boolean emailAlreadyExists(String email) {   Member fellow member = null;   essay {    fellow member = repository.findByEmail(email);   } select handgrip of (NoResultException e) {    // ignore   }   render fellow member != null;  } } 
Member resources interface to last purpose inwards arquillian testing:
package com.broodcamp.jboss_javaee6_war.rest;  import javax.ws.rs.Consumes; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response;  import com.broodcamp.jboss_javaee6_war.model.Member;  @Consumes(MediaType.TEXT_PLAIN) @Produces(MediaType.TEXT_PLAIN) @Path("/members") populace interface IMemberResourceRESTService {   @POST  @Consumes(MediaType.APPLICATION_JSON)  @Produces(MediaType.APPLICATION_JSON)  @Path("/")  populace Response createMember(Member member);  } 

And in conclusion the exam class that creates the archive too deploy it on jboss container:
package com.broodcamp.jboss_javaee6_war.test;  import java.net.URL;  import javax.inject.Inject; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status;  import org.apache.http.HttpStatus; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.extension.rest.client.ArquillianResteasyResource; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.shrinkwrap.api.Archive; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.asset.EmptyAsset; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.slf4j.Logger; import org.slf4j.LoggerFactory;  import com.broodcamp.jboss_javaee6_war.model.Member; import com.broodcamp.jboss_javaee6_war.rest.IMemberResourceRESTService; import com.broodcamp.jboss_javaee6_war.rest.JaxRsActivator; import com.broodcamp.jboss_javaee6_war.service.MemberRegistration;  @RunWith(Arquillian.class) populace class MemberResourceRESTServiceTest {   private Logger log = LoggerFactory    .getLogger(MemberResourceRESTServiceTest.class);   @ArquillianResource  private URL deploymentURL;   @Deployment(testable = false)  populace static Archive createTestArchive() {   render ShrinkWrap     .create(WebArchive.class, "rest.war")     .addClass(JaxRsActivator.class)     .addPackages(true, "com/broodcamp/jboss_javaee6_war")     .addAsResource("META-INF/test-persistence.xml",       "META-INF/persistence.xml")     .addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml")     // Deploy our exam datasource     .addAsWebInfResource("test-ds.xml");  }   @Inject  MemberRegistration memberRegistration;   @Test  populace void testCreateMember(    @ArquillianResteasyResource IMemberResourceRESTService memberResourceRESTService)    throws Exception {   Member newMember = novel Member();   newMember.setName("czetsuya");   newMember.setEmail("czetsuya@gmail.com");   newMember.setPhoneNumber("1234567890");    Response reply = memberResourceRESTService.createMember(newMember);    log.info("Response=" + response.getStatus());    Assert.assertEquals(response.getStatus(), HttpStatus.SC_OK);  }  } 

To run that nosotros ask the next dependencies:
For arquillian testing:
<dependency>  <groupId>junit</groupId>  <artifactId>junit</artifactId>  <scope>test</scope> </dependency>  <dependency>  <groupId>org.jboss.arquillian.junit</groupId>  <artifactId>arquillian-junit-container</artifactId>  <scope>test</scope> </dependency>  <dependency>  <groupId>org.jboss.arquillian.protocol</groupId>  <artifactId>arquillian-protocol-servlet</artifactId>  <scope>test</scope> </dependency> 
For residual testing:
<dependency>  <groupId>org.jboss.arquillian.extension</groupId>  <artifactId>arquillian-rest-client-impl-3x</artifactId>  <version>1.0.0.Alpha3</version> </dependency>  <dependency>  <groupId>org.jboss.resteasy</groupId>  <artifactId>resteasy-jackson-provider</artifactId>  <version>${version.resteasy}</version>  <scope>test</scope> </dependency>  <dependency>  <groupId>org.jboss.arquillian.extension</groupId>  <artifactId>arquillian-rest-client-impl-jersey</artifactId>  <version>1.0.0.Alpha3</version>  <scope>test</scope> </dependency> 

To run the exam nosotros ask to create a maven profile every bit follows:
<profile>  <!-- Run with: mvn create clean exam -Parq-jbossas-managed -->  <id>arq-jbossas-managed</id>  <activation>   <activeByDefault>true</activeByDefault>  </activation>  <dependencies>   <dependency>    <groupId>org.jboss.as</groupId>    <artifactId>jboss-as-arquillian-container-managed</artifactId>    <scope>test</scope>   </dependency>  </dependencies> </profile> 

arquillian.xml to last salve within the src/test/resources folder.
 <?xml version="1.0" encoding="UTF-8"?> <!-- JBoss, Home of Professional Open Source Copyright 2013, Red Hat, Inc.   and/or its affiliates, too private contributors yesteryear the @authors tag. See   the copyright.txt inwards the distribution for a total listing of private contributors.   Licensed nether the Apache License, Version 2.0 (the "License"); you lot may non   purpose this file except inwards compliance alongside the License. You may obtain a re-create   of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required   yesteryear applicable police line or agreed to inwards writing, software distributed nether the   License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS   OF ANY KIND, either limited or implied. See the License for the specific   linguistic communication governing permissions too limitations nether the License. --> <arquillian xmlns="http://jboss.org/schema/arquillian"  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  xsi:schemaLocation="http://jboss.org/schema/arquillian         http://jboss.org/schema/arquillian/arquillian_1_0.xsd">   <!-- Uncomment to conduct maintain exam archives exported to the file organization for inspection -->  <!-- <engine> -->  <!-- <property name="deploymentExportPath">target/</property> -->  <!-- </engine> -->   <!-- Force the purpose of the Servlet 3.0 protocol alongside all containers, every bit it    is the almost mature -->  <defaultProtocol type="Servlet 3.0" />   <!-- Example configuration for a remote WildFly representative -->  <container qualifier="jboss" default="true">   <!-- By default, arquillian volition purpose the JBOSS_HOME surroundings variable.     Alternatively, the configuration below tin last uncommented. -->   <configuration>    <property name="jbossHome">C:\java\jboss\jboss-eap-6.2</property> <!--    <property name="javaVmArguments">-Xmx512m -XX:MaxPermSize=128m --> <!--                 -Xrunjdwp:transport=dt_socket,address=8787,server=y,suspend=y --> <!--             </property> -->   </configuration>  </container>   <engine>   <property name="deploymentExportPath">target/deployments</property>  </engine>  </arquillian> 
And invoke maven as: mvn create clean exam -Parq-jbossas-managed
Next
Previous
Click here for Comments

0 komentar:

Please comment if there are any that need to be asked.