banner



How To Write Junit Test Cases For Rest Services

In this example, we shall show users how they can test a REST service with the aid of the JUnit. Nosotros will utilize the Bailiwick of jersey and Residue assured for this example.

i. Introduction

In the previous examples written by me, nosotros have seen lot of things and scenarios which we tin can test with the help of JUnit. If yous are looking at this case, then there is a brighter chance that you take already know something well-nigh the JUnit.

In this instance, we will deport a unlike scenario i.e. nosotros will examination our REST API with the help of JUnit. But JUnit alone cannot do the trick. Nosotros need to utilise some of the libraries outside which are built on tiptop of the JUnit to assist test. We will also utilise the Jersey for creating a REST project.

In our case we will be using the REST-assured library. This library is very powerful and enriched with tools to exam our scenario. Nosotros will not cover all the scenarios in this instance, every bit hither we will try to sympathise the bones usage of the Residue-assured .

2. Technologies Used

  • Coffee: Language to write code
  • JUnit 4.12: Testing framework
  • Eclipse: IDE for writing code
  • Jersey 2.25.1: Framework to write the REST services
  • Balance assured 3.0.3: Framework to test the Rest spider web servcies

3. What is Jersey

Every bit per the Jersey website,

To simplify evolution of RESTful Spider web services and their clients in Java, a standard and portable JAX-RS API has been designed. Bailiwick of jersey RESTful Web Services framework is open up source, production quality, framework for developing RESTful Spider web Services in Java that provides back up for JAX-RS APIs and serves every bit a JAX-RS (JSR 311 & JSR 339) Reference Implementation.

In unproblematic words, we will utilise Bailiwick of jersey to create a Residuum project and and so we will test those API using REST-bodacious in our example.

4. What is REST assured

REST-bodacious is a library to exam the Remainder API's. It provides diverse methods like go(), body(), when(), then() to examination the diverse scenarios. We will see below in our example how we tin apply these to examination.

five. Project Setup

Tip
Yous may skip project creation and leap directly to the beginning of the instance below. Simply we recommend to follow all steps.

Since nosotros are using the Jersey, nosotros will create Maven project with the help of the eclipse. First of all, we create a Maven project. Click File -> New -> Maven project, you will come across the beneath screen. We do not have to practise anything on the screen so, we will click on Side by side push button.

JUnit REST Web Setup 1

Figure i: JUnit REST Web Setup 1

On this screen, we need to add together the Classic. On this nosotros will click on Add Classic… button.

JUnit REST Web Setup 2

Effigy two: JUnit Rest Spider web Setup 2

We will presented with the following screen. Simply add together the details as mentioned and click on OK button.
Archetype Group Id: org.glassfish.jersey.archetypes
Archetype Artifact Id: jersey-quickstart-webapp
Classic Version: 2.26-b04

JUnit REST Web Setup 3

Figure 3: JUnit REST Web Setup 3

Later on clicking on the OK button you will meet the added classic in the window equally shown below.

JUnit REST Web Setup 4

Figure four: JUnit REST Spider web Setup four

Select it and click on Adjacent button. On this screen make full in all details as shown and click on the Finish push.

JUnit REST Web Setup 5

Effigy 5: JUnit Balance Web Setup 5

Nosotros are fix with our sample Residual projection. But for this instance, we volition make some necessary changes.

6. JUnit Example for REST Web Services

Allow'southward start editing our projection that is built using the steps above. Starting time of open pom.xml file and add these lines to it.

pom.xml

<!-- https://mvnrepository.com/artifact/io.remainder-assured/residue-assured --> <dependency> <groupId>io.rest-assured</groupId> <artifactId>rest-assured</artifactId> <version>3.0.3</version> </dependency>  <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>four.12</version> <scope>examination</scope> </dependency>        

Here we are really, adding dependency foe JUnit and REST-assured.
Also we need to un-annotate the below line from pom.xml file. This will actually assist in testing the json output

<dependency> <groupId>org.glassfish.jersey.media</groupId> <artifactId>bailiwick of jersey-media-moxy</artifactId> </dependency>        

6.1 Coffee Classes

We will create a model grade that will help us to test our case. This is a simple class with iv variables and their getters and setters.

Employee.coffee

package com.javacodegeeks.junitrestweb;  public class Employee {      individual Long id;     individual Cord firstName;     private String lastName;     individual String designation;      public Employee() {     }      // getters and setters }        

Now nosotros volition create a Remainder service for the Employee class.

EmployeeResource.java

package com.javacodegeeks.junitrestweb;  import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType;  @Path("employee") public grade EmployeeResource {      @Get     @Produces(MediaType.APPLICATION_JSON)     @Path("/{id}")     public Employee getEmployee(@PathParam("id") final Long id) {         last Employee emp = new Employee();         emp.setId(id);         emp.setFirstName("Vinod");         emp.setLastName("Kashyap");         emp.setDesignation("CEO");          return emp;     } }        

In this class we are creating a method that will exist called equally an API from outside.
Line 9: we are using the @Path annotation of the Jersey, which specifies that the path proper noun will be used to access the API. In our case it is employee.
Line 12: specifies that we are using the Become protocol of Residuum.
Line 13: specifies that this method volition produces the output as a json. We tin specify any blazon like text, html, xml.
Line xiv: specifies that we will utilise this path to access this method. {id} defines that we need to pass the id so together with the service so url becomes /employee/12.

vi.2 JUnit Test Form

Finally, we need to create a test course that volition test the methods of higher up class.

EmployeeRestTest.java

package com.javacodegeeks.junitrestweb;  import static io.restassured.RestAssured.get; import static org.hamcrest.CoreMatchers.equalTo;  import org.junit.BeforeClass; import org.junit.Test;  import io.restassured.RestAssured;  public class EmployeeRestTest {     @BeforeClass     public static void init() {         RestAssured.baseURI = "http://localhost";         RestAssured.port = 8081;     }      @Exam     public void testUserFetchesSuccess() {         become("/junitrestweb/webapi/employee/12")         .then()         .trunk("id", equalTo(12))         .body("firstName", equalTo("Vinod"))         .body("lastName", equalTo("Kashyap"))         .body("designation", equalTo("CEO"));     } }        

Allow'southward clarify our class and run across what is going here. As nosotros are using the REST-assured for testing this case, we have used its API here in this course.

  • Line 12: @BeforeClass notation is used to do all our initialization earlier our test cases start to execute. This method will execute only once but before executing all exam cases.
  • Line 14-15: In these lines we are using the properties for our API. Instead of putting the aforementioned URL in all test cases we simply initialize them using the RestAssured variables. There are other three properties that we can utilise.

    RestAssured.basePath = "/junitrestweb";
    RestAssured.authentication = basic("username", "password"); // username and password hallmark
    RestAssured.rootPath = "x.y.z";

  • Line 20: Here nosotros are using the go() method of the Remainder-bodacious library. Information technology simply gets the URL.
  • Line 21: So when get() is executed, we then use then() method to specify that whenever we gets something what we accept to do adjacent with that matter.
  • Line 22-25: These lines basically tests the body of the json that is generated against the values specified here.

It covers the main example of the Remainder spider web app. Merely before running this instance we demand to change ane more thing that is auto generated by the magician we have used above. In web.xml file we need to edit ane line before proceeding.

web.xml

<init-param> <param-name>bailiwick of jersey.config.server.provider.packages</param-name> <param-value>com.javacodegeeks.junitrestweb</param-value> </init-param>        

We have edit the line 3. Simply write the package proper noun used in our instance.

half dozen.3 Running the example

Earlier we start testing, we need to run our web projection on the web server. In our case, nosotros are using the tomcat for testing. Simply deploy the application on the tomcat and we are ready to test our example.

After running, right click on EmployeeRestTest.coffee course and Run Every bit -> JUnit Test. Our case will succeed with the following output shown in the eclipse JUnit window.

JUnit REST Web Output

Figure 6: JUnit REST Web Output

7. Decision

In this example nosotros take seen how we tin create a simple Residual projection then examination it using the library known as Residuum-bodacious. We accept learned the basic usage of the Bailiwick of jersey framework which helps in creating the REST web services.

References for the libraries used in this instance fare are given below. Users are advised to visit the references for more detailed knowledge of the libraries.

8. Download the Eclipse Project

This is an JUnit instance for testing the Residue web services.

9. References

  • My JUnit Tutorials
  • Residual Assured Library
  • JUnit Framework
  • Jersey Framework

How To Write Junit Test Cases For Rest Services,

Source: https://examples.javacodegeeks.com/core-java/junit/junit-example-rest-web-services/

Posted by: howejuserebeaven.blogspot.com

0 Response to "How To Write Junit Test Cases For Rest Services"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel