I have a REST client in Java that is ready to connect to a REST server, send a specific request and get a response back. However, the actual REST server is not available during development time (it is hosted by a 3rd party and only available in the isolated local net of the target machine) and we still want to test connectivity and interaction with the server.
Can you point me to a product or technology that in the first place lets me quickly create a fake REST server (or at least mock it) according to the specification of the REST call parameters? I did some research on the web but haven't had a "yes, this is it!" moment yet.
You can use any rest mocking framework to achieve this. As per my experience
Wiremock is the best framework for RES API Mocking.
http://wiremock.org/
You can use mockwebserver library by square. It's pretty simple to use and do exactly what you attempt to do.
Little usage sample:
MockWebServer server = new MockWebServer();
server.enqueue(new MockResponse().setBody("hello world"));
server.start();
For client testing, I would recommend a tool like SOAP UI or Postman. But for mocking the REST service itself, I would actually recommend just creating some dummy endpoints in your Java web application and using that. At each endpoint you could do something hard code a simple response, in JSON, XML, or whatever would make sense with your service. Then, when you finally come to actual development, you will already have a functioning framework for your REST service. You would just need to fill in the missing pieces.
This makes sense because you are going to need to setup REST support in your Java code anyway, and the amount of effort to just add stubs should be minimal. This approach is also attractive from the point of view that it avoids any potential surprises from switching from a mock REST service to the actual one.
Related
I've written a REST proxy that calls a REST service
#RequestMapping(value = { "session" }, method = {RequestMethod.GET)
#ResponseBody
public String sesionGet(HttpServletRequest request, HttpServletResponse httpServletResponse) {
//call rest webservice
PostResponse postRequest = IncomeAccessUtils.postRequest(/*call web esrvice*/);
I need to do an integration test on that proxy but sometimes the server at which the external web service deployed on is down. Can I mock a response from webservice call ? I am using spring-test-mvc and/or rest-assure frameworks for testing.
Yes there are several way of doing this in Java.
Without much details I would recommend looking at betamax - it records any network integration and saves it for replay later. You can pass in whethere you want to run live or use the recording. (In one project we ran against real servers in the CI env but used version controlled recordings when running tests locally.)
SoapUI is another tool capable of mocking a web server. This may be a good choice if you work with WSDL and/or SOAP. (Poor you! :-) ) There are numerous such alternatives for rest out there but I don't have it fresh in my head.
A simplistic alternativ is to run pythons simple HTTP server: python -m SimpleHTTPServer 8888. It just serves whatever is in the directory where it was started. Put your reponses there as files and you are good to go. (Work with simple stuff but if headers etc is important not so good. Also not good at simulating failed calls.)
Finally if you are fine with not making the web call at all you can have mocks on the inside. If you use a dependency injection framework like Spring it is easy to run a version with mocked implementations of a backend call instead of the real one.
I need to consume REST API. There are many REST clients for Java. Are there any areas of concerns before proceeding this?
You can use HttpClient for that. However, if you are working on a spring enabled project, I would recommend using RestTemplate.
Rest template provides an abstraction over HTTP client as a result of which you will not have to deal with serialization/deserialition, error handling, SSL configuration in every part of code where you make a REST call. You will just need to configure those with REST template configuration once and not worry about it. This makes your code clean and easily maintainable in case you wish to change the way your application talks to the back-end restful application in future.
So, here's the thing.
There's a REST service I'm using that is supposed to be tested and I can't access the code.
I've made some kind of library in java so I can interact with that service, but I need to unit test my library (actually it's still not implemented, I'm using TDD) so I can know for sure it works.
How can I do it so I don't mess up with the service (I don't want to create nor delete anything)?
Should I use some kind of mock or stub? If so, how can it be done?
Thx!
I use the Jersey test framework to test - if you have written your code with Jersey. It runs grizzly in the background.
You could use HttpUnit's PseudoServer to create fake responses.
Or you could use HttpClient to generate post and get requests to your running service.
You can use a mocking framework (I like Mockito) to mock your API endpoint library. Then you can use traditional junit tests to ensure that your library is making the expected API calls.
If you want to actually make the HTTP calls, there are few other libraries you can use (Jersey client was already suggested).
Is rest assured a thing you wanted to find?
My organization uses spring to generate our mock rest services. Spring MVC test framework (formally spring social test) works very well. However if you aren't already using spring i'd suggest Jmock, mockito, or easy mock to just fake a response.
I dislike the idea to use a mock since it leaves out the HTTP stuff. Best is using a mock server like enter link description here. It is a bit tricky first but once you have your test case up and running it is a breeze. I use random ports to start the mock server so one can run tests in parallel.
I'm getting ready to dive into testing of a RESTful service. The majority of our systems are built in Java and Eclipse, so I'm hoping to stay there.
I've already found rest-client (http://code.google.com/p/rest-client/) for doing manual and exploratory testing, but is there a stack of java classes that may make my life easier? I'm using testNG for the test platform, but would love helper libraries that can save me time.
I've found http4e (http://www.ywebb.com/) but I'd really like something FOSS.
You can use REST Assured which makes it very easy to test and validate REST services in Java from JUnit or TestNG. E.g. let's say that a GET request to a service called "/lotto" returns the following JSON
{
"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]
}]
}
}
then you can make the request and validate the response (in this case that lotto id equal to 5) with REST Assured like this:
expect().body("lotto.lottoId", equalTo(5)).when().get("/lotto");
Would JMeter be an option? It has HTTP Request samplers that support all of the HTTP methods and assertions to validate the response.
Another alternative might be something like soapUI which has an API that could be integrated with your test cases, though I haven't tried it.
CXF apparently has support for REST. I haven't tried the REST support yet myself, but I think CXF is a superb, flexible, standards-based webservice implementation.
Another informal option to test your REST services is by using the Firefox RESTClient Add-on.
Postman REST Client for Google Chrome is another option.
Apparently rest-client has a library built in. I'm using that with testNG and XStream and it seems to be exactly what the doctor ordered.
I was working today around the unit testing of a rest service, I needed to test the deployed server in order to check some concurrency requeriments, so I needed to test the deployes rest service.
At first I tried the solution sugested by Johan, and started with REST Assured with some succes, but look for more documentation, I found this:
http://uttesh.blogspot.com/2012/09/spring-rest-web-service-test.html
its based on a spring library, so if you are using spring, you'll keep using the stuff from the same vendor, which is always nice.
Also I found the libs from spring easier to understand than REST Assured, but it's just me ;)
I am building a REST based API (Read only) for accessing services of my application. I plan on writing a web application that will leverage these APIs to provide basic information on the status of the application. I plan to use AJAX (using jQuery) to show the information.
Originally I planned on using Grails, Spring MVC, RoR or one of the web frameworks to handle the back end of my application. The REST APIs I will be providing though are already built on a stanalone REST framework so I would only be leveraging the web framework for the core application and not the business logic. In the future, I might need the server side framework to handle other tasks but for now most of the work is done in the REST APIs.
My question is, should I bother with using a web application framework on the server side? I should be able to make all the API calls I need from AJAX directly from the browser. I cannot think of much I would need to do on the server side. Would it make sense to have the application be standard HTML + AJAX + REST?
Its hard to say without actually knowing more about your current setup. This is what your situation sounds like:
You already have an app ready to go with all of the business logic contained. Sounds like its written in Java?
You already have the services written and exposed through a REST api using some other standalone framework. Meaning that if you wanted to, you could access the data right now with the browser without any extra work.
You have not yet built the web application, but when you do, it will get all of its content from the REST api using XHR and jquery. I say that, because otherwise, I would think that you would already be using some kind of framework to generate the other content.
If I am correct in my assumptions, then I would say that you have no need for an additional framework layer. Grails, RoR, SpringMVC my use ajax, and aid in exposing REST services, but the bulk of what they provide is an easy way to make an application that must generate html on the server, deal with form submissions, and handle sessions in a request/response cycle. It doesn't really sound like you'll be doing any of that, and it will likely make your app more complicated.
If you did at some point need the things that rails etc. provides, I would say that you may not need to use rails to expose the rest apis you have now. You could use rails just for what you need, and continue to use what you have for the REST api.
Well, the AJAX calls need to pull data from a server somewhere. If the goal is to avoid a complicated setup on the server side, CherryPy can keep the server side code VERY small.
I've written a simple exapmle below. The first class would be where you put the logic for your ReST API. The code below the class is all you need to get the server up and running.
Install Python 2.6, save the code below to restExample.py. Then in your command line run the python file by doing "python restExample.py". Point your browser to http://localhost:8080/blog/999 and see some JSON come back.
import cherrypy
import json
# Create the controller
class Blog_Controller(object):
def get(self, entryID):
cherrypy.response.headers['Content-Type'] = 'application/json'
return json.dumps({'title':'Entry Title from DB', 'entry_text': 'Text From DB'})
def update(self, entryID, titleFromPOSTFormInput, textFromPOSTFormInput):
# Update DB with passed in arguments. entryID comes from URL,
# other two entries come from POST
cherrypy.response.headers['Content-Type'] = 'application/json'
return json.dumps({'success':True})
# Setup URL routes
d = cherrypy.dispatch.RoutesDispatcher()
d.connect(name='blog_entry', route='blog/:entryID', action='get',
controller=Blog_Controller(),
conditions={'method': ['GET']})
d.connect(name='blog_entry', route='blog/update/:entryID', action='update',
controller=Blog_Controller(),
conditions={'method': ['POST']})
config = { '/' : { 'request.dispatch': d } }
cherrypy.tree.mount(root=None, config=config)
# Start the webserver
engine = cherrypy.engine
try:
engine.start()
except:
sys.exit(1)
else:
engine.block()
It sounds like this might be a good use case for GWT with Restlet.
Forgive me for tooting my own horn, but if you are doing AJAX REST stuff with jQuery, you should probably check out my JSON-REST plugin:
http://plugins.jquery.com/project/rest
If you are getting XML back, then this won't be as useful, but you may still be able to adapt some of the code to your needs.