I am using TestNG to write test cases.
I want to write a test case for my Rest API, and my server is not up. It means no one is giving me a response.
I have URL which I can hit. I know the response also what should come as a response when I hit the URL.
It is possible using directly hit the API, fetch the response and then from the response fetch the body and check it whether it is true or not?
I don't want that way means my server is not.
Is this any way to mock the Rest Service and implement that?
There are numerous ways how to approach your issue. Whether they would be easy or complicated depends on what was the way your service under test was implemented.
You can configure the required mock using Soap UI for example or WireMock. Unlike the previous ways you can build your mocks automatically if the developers used frameworks like Swagger (Swagger mock server) to describe the REST service.
Recently I've made use of RestAssured for testing Rest API and it seems to be pretty useful.
However I've a query regarding testing rest end-points. We don't deploy our services locally onto a server.
We write the unit test and integration tests and test it and deploy it on a separate dev1 environment.
What I want is to write an integration test that will post a request and test the rest-endpoint using restassured.Kindly advise. Thanks.
P.S. We don't have local server where we can deploy and hit the rest end-point.
Local or remote server doesn't matter I hope. Pls take a look at docs https://github.com/rest-assured/rest-assured/wiki/Usage
You can set the remote server URL globally for all tests using RestAssured.baseURI="<BaseURL>" or you can pass the full URL in RestAssured method itself like get("http://baseURL/service1")
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
What is the best way to test REST services in Java? What approaches and tool set do developers usually take?
Also if you are writing rest clients that call into third party REST services. What is the best way to test REST clients. Do you have JUnit tests that communicate with a third party REST service. You could run into the risk of service not being available/or production REST service cannot be access without certain credentials.
I suggest that you take a look at REST Assured for automated testing of REST services. The following example is copied from it's web page:
For example if your HTTP server returns the following JSON at “http://localhost:8080/lotto/{id}”:
{
"lotto":{
"lottoId":5,
"winning-numbers":[2,45,34,23,7,5,3],
"winners":[
{
"winnerId":23,
"numbers":[2,45,34,23,3,5]
},
{
"winnerId":54,
"numbers":[52,3,12,11,18,22]
}
]
}
}
You can easily use REST Assured to validate interesting things from response:
#Test public void
lotto_resource_returns_200_with_expected_id_and_winners() {
when().
get("/lotto/{id}", 5).
then().
statusCode(200).
body("lotto.lottoId", equalTo(5),
"lotto.winners.winnerId", containsOnly(23, 54));
}
See the getting started and usage guides for more information.
If you have implemented your server app using Spring Boot, you may also find the blog post about Integrating Testing a Spring Boot Application that I wrote a couple of years ago interesting. It shows how Spring Boot test support starts an embedded web server and deploys the application to it before executing REST Assured based tests against the REST API. In other words, neither do you have to manually start a web server, nor do you need to re-deploy the app between tests. As a matter of fact, you do not even have to create a .war or .jar file between your code changes in order to validate REST API changes.
1. What is the best way to test REST services in Java? What approaches and tool set do developers usually take?
You can test your rest services by first testing the actual code and functionality of the service itself and make sure it is functioning properly using any unit testing library applicable to your project.
Next, you would publish the REST service and try accessing the RESTful methods using a http client of some sort.
Generally, the easiest way is just a plain old browser. Type in the url and information if it is a GET or PUT based request. If it is a post, you can use browser plugins or dev tools to help add data to the body of the request or header as needed and validate you are getting the response you expect. If it works in a browser, it should perform similarly with any HTTP capable client you choose.
2. Also if you are writing rest clients that call into third party REST services. What is the best way to test REST clients. Do you have JUnit tests that communicate with a third party REST service. You could run into the risk of service not being available/or production REST service cannot be access without certain credentials.
You can generally use any sort of Http Client library you wish based on the language you are using. The main pitfall to look out for with testing of a REST client is to make sure you are capturing the Response returned by the REST service and checking the status. If it is good, you will get a 200, server error 500, etc. etc.
I recommend taking a look at W3C or Wikipedia status code information https://en.wikipedia.org/wiki/List_of_HTTP_status_codes or https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html.
Further, you should understand the types of responses that are possible to be returned from the particular service. This should be available in the api documentation for the service. The api should also explain any sort of credentials or requirements that need to be passed through the header or as a parameter to the REST call.
Understanding how REST works and HTTP in general would be good starting points.
There are several ways to test REST API, depends on your needs:
Jersey Test - you can execute and test REST API calls with in-memory HTTP server. You'll need to mock your code - use Mockito (Jersey 1.19 Test configuration - mock classes) or in-memory testing database.
Rest Assured - the main drawback is that you need to run REST API project separately/individually from tests (RestAssured testing without running Tomcat)
Tools with UI - SOAP UI or Postman
Swagger - generates interactive documentation - web page where you execute REST methods with prepared data according annotated methods in a code.
Use Spring Boot for developing REST services. It has various tools for testing which you can use out of the box without excessive configuration.
You can create a REST Service mock using SoapUI. Also, if you needed to run this test through maven, you can use soapui-maven-plugin to instanciate do soapui service automatically
For part 2 in your question, the correct answer depends on various factors. You would want to consider both the resolution of the mocking and the time spent writing and maintaining the tests.
Client library
The choice of HTTP-client will affect your options - some klients (like Spring RestTemplate) offer built-in mocking support. If you have a service definition like a swagger or RAML file, you'd want to generate the client.
Project configuration
The most thorough way is to actually let the application make HTTP calls to real endpoints, involving the full stack. If so, configure your project so that the client URLs are injected in a per-environment (or profile) fashion.
Mock endpoints
You want mocking per unit test. No 'deployable mocks' which serve multiple unit-tests. Services are mocked on a localhost port - preferably randomly selected so that parallell testing is possible (i.e. on jenkins).
Mock data
To save time, for deep data structures, it is very desirable that mock data is read from a file, rather than constructed programmatically. Files are much easier to work with, especially if you enable request/response logging, fixing bugs and so is faster.
Mocking
Some frameworks are loosely coupled to the service, as in they are strictly not aware of the nature of the service. Typically you'd mock a respons at some path which is coded in the unit test. This is like Wiremock and most of the test frameworks I've seen.
Whereas other tools work directly on class service definitions, basically you'd use a tool like Mockito to mock an object directly (but wrapped in a real endpoint). This should be less error prone, but requires the classes to be present (as test dependencies). I've written a tool like that, for comparison.
I want to write an integration level test for a rest method using MockRestServiceServer. My rest method is a proxy, it ends up creating a restTemplate via a static helper method and proxys the request to a third party. I want to mock out that third party. Actually two different rest calls are made to different parties with different configurations to service the request.
I want to use MockRestServiceServer, but it expects me to pass in the restTemplate, which is constructed within my integration test. I can try to use mocks to ensure that my own restTemplate is used, but now I have to pull in 4 new maven packages and write a bit of code to do the inject safely, and make sure that a different restTemplate is used for the two different external service calls my proxy does. It also requires me to know a little bit about my code and thus makes my integration test less of a black box then I would prefer.
Is there a cleaner way to mock the services? I know my approach could work, but it's just feeling overly cumbersome. Is there a way to mock this without having to inject the RestTemplate ahead of time?
If you don't want to redesign the part where you create instances of RestTemplate then you can parametrize out address of the external service and mock the entire external service using tools like Wiremock.
Using Wiremock, you actually run an embedded HTTP Server on a specific port. You can also tell Wiremock to return specified response when predefined request is made. It basically is just a mock, but over HTTP.
This way you would get a good integration test that would not only test your typical Java code but also entire communication (like JSON (de)serialization). I use Wiremock (and related) extensively at work and they do work like a charm.
I am searching for a simple framework which is able to mock JSON responses for specific URLs and therefore starts an in-memory server. E.g. the framework could start a node.js server or similar.
I need a physical server since the unit tests are running against an external application (using selenium) and this application has a dependency to a JSON interface. The application itself is iPhone-App running inside of simulator and communicates to a REST interface.
Is there an existing framework for this or what would be the best approach given that I need to execute the tests with jUnit.
You can start a stub server, given that you can configure the JSON URL in your client application.
Have a look for example at:
https://github.com/dreamhead/moco
https://stubby4j.com
You can start these in your maven build during the pre-integrationtest phase and shut them down in post-integration test phase.
You can use npm package stubby-db. What you need to do is;
Install : npm install stubby-db -g
Mapping : Create a request response mapping which is quite easy. Specify the path of response file having JSON response.
Run the stub server: stubbydb
That's all. However since you just want to run it for your unit tests only which doesn't require much performance, you can also use wiremock. It starts internally, and you never feel like you are running an external application.