Mocking REST call to another rest-service - java

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.

Related

How do I test a REST client?

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.

can i mock a SOAP and rest webservice reponses with file stream from local directiry

I have a requirement to mock webservice call. Here instead of actual webservice call to dummy server and server should reply my response xml response file from local directory.
Our project used that approach (used for mocking external Webservices which were not available on local workspace).
Short answer is yes, but how to implement would depend on your code.
First , we created a interface to call webservice, so that we can create 2 implementations, one actual( which calls external service) and one Test ( which calls an internal WebService which reads from file).
Next, we created a test webservice which we hosted on the same server. Now the logic was simple. Based on input , we used to read the correct response from file. You can build whatever logic you want, our framework was designed to support multiple webservices.
Lastly, in our code, kind of like spring, we used to point to test service ( via interface) instead of actual service. So we could read from file and provide a response. When external interface was available, we would simply switch the configuration and we were good.
Ofcourse, this is over simplification, but I hope you get the gist.
You have two ways of proceeding :
mock the ws from the client side by providing an mocked implementation of the client ws.
mock the the ws from the server side by creating a mocking instance of the ws.
Mocking the call from the client side is simple. You create an common interface with the ws methods you want to call. And you create two implementations of this.
One with the effective call to the ws and another with stubbed responses coming from local files.
Mocking or simulating the ws from the server side is not much complicated but it is not the same approach. You can hard code it but it is not a secure solution when you must mock it again. You also can use a webservice simulator instead of your webservice. You will not query you webservice but another.
SOAPUi can help you to achieve this task by mocking your webservice responses.
Example for SOAP mocking
To use a local file as response, you should use SOAPUI response scripting.
SOAP reponse mocking

How to debug a JUnit test class for RESTful Web Services in IntelliJ IDEA?

I am just started to write JUnit test cases.Now I am writing a test method to test RESTful web service in java using the IntelliJ IDEA. My directory structure as this.
I am calling the web service from my test case as:
Response response = target.path("groups").path("registergroup").request().accept(MediaType.APPLICATION_JSON).post(Entity.json(stringEmp.toString()));
String output = response.readEntity(String.class);
I have added the multiple breakpoint in this test method and source classes.
Is it possible to jump Webservice classes from above request point?
If possible then how can I do that?
I am using the embedded jetty server to test which is also running from this module.
Testing REST services using JUnit only is in my opinion not worth the effort, because you usually have to mock a lot of the REST library internals in order to make it work, and it's very hard to test some of the service behavior anyway (e.g. what happens when the client specifies the wrong Content-Type or Accept headers).
Assuming you are using Jersey, you have two options :
use JerseyTest
use Arquillian
My personal preference goes to Arquillian because (among other things) the resulting tests are completely independent from what is being tested (i.e. you can change the implementation of the service and the REST library without changing the tests).

JBehave for testing REST web-application

I'm working on a project which receives json data via REST and after some processing sends them further. I.e. it has both HTTP-server and HTTP-client parts.
Now I'm told to add integration tests to them and was proposed to use Citrus framework. I see it has citrus-http module, but after setting all things up I do not feel very happy with it for I do not want write tests in XML (while it is required they should not be written in compiled code).
So I started to think about using JBehave, but I have no experience with testing http with it - and I could not find necessary examples at once. It seems I need to start http server, send some data with http client and check the result on the server. But are there any modules or JBehave-friendly framework for providing this "http" part - or I should create them from scratch?
You could use WireMock. It's a library that works really good with http requests. You could start your WireMock server in #BeforeStory and it will start recording and then shut it down in your #AfterStory in your steps class. You will have your response for your request stored in a file and it will be easy to work with.
Your assumption that Citrus only supports XML tests is wrong. Citrus also provides a Java DSL for writing tests. Here is an example:
#CitrusTest
public void testHttp() {
http().client("http://localhost:8080")
.post()
.contentType(MediaType.APPLICATION_FORM_URLENCODED)
.payload("name=Penny&age=20");
http().client("http://localhost:8080")
.response(HttpStatus.OK);
}
JBehave is a BDD (Behavior Driven Development) framework and has nothing to do with Http testing in particular. You can combine any Http test library with JBehave

Testing REST service in java

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.

Categories