Fake http responses with cucumber - xmlhttprequest

Say, I have a feature in my app that relies on an external API - I provide an interface, which makes calls to my server, and the server, relying on that, makes some calls to some external API and responds something to client. If I wanna write an acceptance test with cucumber for that, how can I stub the calls to that external API, so, e.g. any GET call to https://www.cool-api.io/foo would just immediately return some-predefined JSON response with some predefined headers, any POST request to that url would return a response with some predefined status and headers, etc. How do you do it for acceptance tests if you're using cucumber?

We use WireMock or MockServer for this. You can implement them to stub API calls.
Also, I'd recommend using a framework like Jackson to generate json from domain objects. The benefits of this are not having to maintain json Strings/docs in your code base, and compile time checks on whether you created valid domain objects in your test.

I would probably write my own stub that was able to fake an implementation of the response with the expected content and headers set. If the response object is defined with an interface, then have your hand rolled stub to implement that interface.
Using Mockito for this would probably be to cumbersome in my opinion. Mockito is great, but setting up a complex return value like this may be messy. Hard coding the responses in an implementation of a response interface may be easier.
I would check the actual integration towards the external service using other tooling than Cucumber.

Related

How to write a junit test case to test a rest client?

I have created a spring boot rest client, which basically consumes a rest service. I want to write a junit test case to validate my rest client. I was hoping to intercept the rest request somehow in the junit test case and check if the context in the URL, path parameters, query param and body is correct. i just want to confirm, if anyone uses the rest client, it will make the proper calls to the rest services.
Here are some approaches you can try:
Use #RestClientTest annotation. It will load only the class that contains rest client calls and also configures the application context during the test to provide ways to match the request for verifications.
You can read this article for example
Use WireMock - you can start it at during the setup phase setup the expectations, during the test make the calls and at the end verify that the calls have matched the expected ones. When you make the request to wire mock it will "record" it and store in memory (until you reset it). It also starts on the real port so you should have a port available. For more information read this chapter of the official documentation

How do you write a simple unit test case to handle http404 without accessing the server using any OOP language?

Assume the application consumes a third-party HTTP API.
You likely have a client library that lets you interact with http services. You need to prepare a special sort of object (again if your "any" language is object oriented) (mock object) that would be treated by your code under test as the regualar object.
The only differece is that for your test the method that is responsible for endpoint invocation would always return 404 error.

Resource or Restlet

I am using Restlet 2.2.1 and building Rest services. As you know, Router is used to attach either Restlet or Resource as target.
Router router = new Router( getContext() );
router.attach("/healthcheck1",HealthCheckResource.class );
router.attach("/healthcheck2", new HealthCheckRestlet() );
Then you can implement your logic in handle()
Wondering which is best one to use? I know Resource has a very definite life cycle (doInit, handle, release ...) and good place to implement one time logic like initialization.
Attach a ServerResource subclass rather than a Restlet instance when feasible, for a couple of reasons:
Resources are the natural way to structure RESTful APIs. When you use the #Get, #Put, etc. annotations on a resource class, you're effectively documenting that part of your RESTful API, and there are tools that can extract that information to create online documentation automatically. If you use a Restlet instance, its behavior in response to GET, PUT, etc. is not immediately apparent. Ironically, using a Restlet makes it easier to write APIs that are not RESTful.
A separate instance of the resource class is created for each request, meaning that an instance is normally confined to a single thread, which simplifies reasoning about thread-safety. In constrast, the same Restlet instance will be used for all handle(...) calls, potentially leading to complicated thread-safety requirements.
Because each request gets its own resource instance, the resource methods might need to appeal to internal services that are passed via the application context or injected into the resource (see this Restlet extension).
Incidentally, your comment about "one time logic like initialization" might be a misunderstanding. The doInit method is called for each instantiated resource (i.e., once per request for that resource), not one time only.
Note that I'm recommending against directly subclassing Restlet as an end target for a resource URL, except maybe for trivial resources. Using subclasses of Restlet is a different matter: Attaching a Filter which wraps a resource is fine.

Is testing a service a functional test or an integration test

We have a .Net component that provides functionality. We have a Restful Web API service that the world will use to call that functionality. We wrote tests that use OWIN to call into our Web API controllers.
In the past, I had always called these "integration tests", because the service is a separate component. However, another developer, who I respect, told me that this is not an integration test, but is instead a "functional test".
I looked at the Defintion of Functional Testing and the definition of Definition of Integration Test and neither one was a clear winner to me for what a test of a RESTful service test should be called.
Is it integration or functional? Are there any authoritative sources that can be used to definitively answer this question (because I don't want my question to be closed for "soliciting debate")?
Functional testing is a black box exercise, as stated in the Functional testing definition link you posted. This means that the testing occurs without knowledge of the internal workings of the system (such as the code). You would be interested in whether the API works as expected end-to-end; does the user receive the correct response when they use the API? If the REST API is being tested outside of your system then it is a functional test.
If the API is being tested from your code base then this is testing the integration between two or more modules and thus classifies as an integration test. This might involve testing whether a dependent module is sending the correct data, receiving the expected data and in the correct format.
For more information check out anything from ISTQB which is a recognised body for software testing. Here is a link to an ISTQB glossary: http://www.software-tester.ch/PDF-Files/ISTQB%20Glossary%20of%20Testing%20Terms%202.4.pdf
When you call a rest service to verify that the service returns what it was designed to return, that is a functional test. You are testing the functionality of the service.
If you had a second service or UI that depended on this service, and your tests interacted with this second service or UI to verify that it can properly call the REST API and consume it's data, that would be an integration test.

Inject behavior into WCF After or During identification of WebGet Method to call

I am trying to solve a problem where i have a WCF system that i have built a custom Host, Factory host, instance providers and service behaviors to do authentication and dependency injection.
However I have come up with a problem at the authorisation level as I would like to do authorisation at the level of the method being called.
For example
[OperationContract]
[WebGet(UriTemplate = "/{ConstituentNumber}/")]
public Constituent GetConstituent(string ConstituentNumber)
{
Authorisation.Factory.Instance.IsAuthorised(MethodBase.GetCurrentMethod().Name, WebOperationContext.Current.IncomingRequest.Headers["Authorization"]);
return constituentSoapService.GetConstituentDetails(ConstituentNumber);
}
Basically I now have to copy the Call to IsAuthorised across every web method I have. This has two problems.
It is not very testable. I Have extracted the dependecies as best that I can. But this setup means that I have to mock out calls to the database and calls to the
WebOperationContext.
I Have to Copy that Method over and over again.
What I would like to know is, is there a spot in the WCF pipeline that enables me to know which method is about to be called. Execute the authorisation request. and then execute the method based on the true false value of the authorisation response.
Even better if i can build an attribute that will say how to evaluate the method.
One possible way to do what you want might be by intercepting requests with a custom IDispatchMessageInspector (or similar WCF extension point).
The trick there, however, is that all you get is the raw message, but not where it will be processed (i.e. the method name). With a bit of work, however, it should be possible to build a map of URIs/actions and the matching method names (this is how you'd do it for SOAP, though haven't tried it for WebGet/WebInvoke yet).