RESTeasy + Server mock + ExceptionMapper not found - unit-testing

I have a scenario where ExceptionMapper are used in JAX-RS using RESTeasy 2.0.1.GA . This works all fine.
I'd now like to test the whole thing using RESTeasy's mock mechanism. Unfortunately my ExceptionMapper-provider is not registered. What am I missing?
POJOResourceFactory factory = new POJOResourceFactory(SomeWebResource.class);
Dispatcher dispatcher = MockDispatcherFactory.createDispatcher();
dispatcher.getRegistry().addResourceFactory(factory);
MockHttpRequest request = MockHttpRequest.get("url");
MockHttpResponse response = new MockHttpResponse();
// here my exception is thrown
dispatcher.invoke(request, response);
// but I expect the response to be 404 (which works outside the mock setup)
Assert.assertEquals(response.getStatus(), 404);

Okay, I found the solution. Needed to register the ExceptionMapper manually:
dispatcher.getProviderFactory().addExceptionMapper(SomeExceptionMapper.class);

After struggling with this problem for a few days now, I think it's worth mentioning what #Joe W wrote in the comment of the above answer as it's own answer:
"Note: addExceptionMapper()'s visibility was changed to protected in later versions. dispatcher.getProviderFactory().registerProvider(SomeExceptionMapper.class) works instead."

Related

Assert WebFlux ServerResponse using MockServerRequest

I want to separate router layer from handler layer, so I don't want to use WebTestClient as suggested in this question. I do not think throwing WebTestClient at the problem is the right solution.
In my case, I am using MockServerRequest, which only allows testing for http status code and headers. There is no way to assert the body of the response.
val request = MockServerRequest.builder()
.method(HttpMethod.GET)
.uri(URI.create("/service"))
.build()
StepVerifier.create(myHandler.handleGet(request))
.assertNext { /* and assertThat(it.body()) ... */ }
.verifyComplete()
Is there a way to assert the body? If none then why and what is the alternative?
While debugging, I have noticed that I can see the body (entity). Hence, I have inspected the returned class and its hierarchy. I have realized that casting may solve the problem, and it worked (I am not sure if it is the right way though).
For the code in question:
val request = MockServerRequest.builder()
.method(HttpMethod.GET)
.uri(URI.create("/service"))
.build()
StepVerifier.create(myHandler.handleGet(request))
.assertNext { assertThat((it as EntityResponse<Fleet>).entity())
.isNotNull /* add more assertions */ }
.verifyComplete()

Unit testing Promise task in grails

How do we unit test logic in Promises.task?
task{service.method()}
I want to validate invocation of the service method inside the task.
Is this possible? If yes, how?
I read in the documentation that in unit testing async processes, one can use this:
Promises.promiseFactory = new SynchronousPromiseFactory()
Tried adding it in my setup, but still does not work.
The long way
I've been struggling with this for a moment too.
I tried those:
grails unit test + Thread
Verify Spock mock with specified timeout
Also tried the same solution from the docs as you:
Promises.promiseFactory = new SynchronousPromiseFactory()
All went with no luck.
The solution
So I ended up with meta classing.
In the test's setup method, I mocked the Promise.task closure, so it runs the closure in the current thread, not in a new one:
def setup() {
Promises.metaClass.static.task = { Closure c -> c() }
// ...more stuff if needed...
}
Thanks to that, I can test the code as it wouldn't use multi threading.
Even I'm far from being 100% happy with this, I couldn't get anything better so far.
In recent versions of Grails (3.2.3 for instance), there is no need to mock, metaClass or use a Promise factory. I found out the promises in unit tests get executed synchronously. Found no doc for that, I empirically added a sleep inside a promise and noticed the test waited for the pause to complete.
For integration tests and functional tests, that's another story: you have to change the promise provider, for instance in BootStrap.groovy:
if (Environment.current == Environment.TEST) {
Promises.promiseFactory = new SynchronousPromiseFactory()
}
Like Marcin suggested, the metaClass option is not satisfactory. Also bear in mind that previous (or future) versions of Grails are likely to work differently.
If you are stuck with Grails 2 like dinosaurs such as me, then you can just copy the classes SynchronousPromiseFactory and SynchronousPromise from Grails 3 to your project and then the following works:
Promises.promiseFactory = new Grails3SynchronousPromiseFactory()
(Class names are prefixed with Grails3 to make the hack more obvious)
I'd simply mock/override the Promises.task method to invoke the provided closure directly.

Testing Dropwizard Post method for URL resource

I have a url resource that has a GET and a POST method. To test the GET method I followed this article https://github.com/dropwizard/dropwizard/blob/master/docs/source/manual/testing.rst
But is there a way to test the POST method? Also I am using iceweasel on Debian and would like to know if there is a 'POSTMAN'(chrome) like plugin that can be used to test url resources??
You can use following for the entity:
Entity<?> entity = Entity.entity(person, MediaType.APPLICATION_JSON_TYPE);
final Response response = RESOURCES.target("/person/blah")
.request()
.post(entity);
You should be able to use the same technique as GET - just switch to POST:
#Test
public void testPostPerson() {
assertThat(resources.client().target("/person/blah")
.request().post(Person.class)).isEqualTo(expectedResponse);
verify(dao).createPerson("blah");
}
On linux I often find it useful to just use curl from the command line for testing REST resources. See:
The curl man page
A curl POST example

Http.Context with FakeApplication and illusive mock method

In my tests I create a fake application per test method:
#Before
public void startFakeApplication() {
this.fakeApplication = fakeApplication();
start(this.fakeApplication);
}
#After
public void killFakeApplication() {
stop(this.fakeApplication);
this.fakeApplication = null;
}
Some of the tests use functionality that checks if the request is secure or not:
public boolean isHttps() {
Http.Request req = Controller.request();
return req.getHeader("x-forwarded-proto") != null
&& req.getHeader("x-forwarded-proto").contains("https");
}
That fails saying:
There is no HTTP Context available from here
Which is pretty strange, since it's running on a fake app, why can't it know that and create a fake request?
Oh well, I found this: Play framework 2.2.1: Create Http.Context for tests which introduced me to the mocking approach, so I was eager to give it a go and try to mock the Http.Context in the same way, the problem is that I can't seem to find the mock method...
In that thread he's using import static org.mockito.Mockito.* (which is where I assume the mock method is located) but I don't have that package, org.mockito only has one sub package named internal and I can't find any mock method there.
In the official documentation of Play! the only place talking about it is the Scala Test section and they use: import org.specs2.mock._ but there too I wasn't able to locate this mock method.
I'm using Play 2.2.2 (java).
Any ideas? Thanks.
I solved the same problem adding to my build.sbt the library dependency of Mockito:
libraryDependencies += "org.mockito" % "mockito-core" % "1.10.19"
Then I run play compile and play eclipse and magically the mockito library became available after refreshing the whole project in Eclipse.
And yes, mock() is a method of org.mockito.Mockito.
I had the same problem of Play not locating the mock function, and eventually realised that I hadn't extended my test class with Mockito;
import org.specs2.mock._
class TestClass extends Specification with Mockito
Just thought I'd add this as it has taken me ages to resolve and the above solution didn't work for me ......may save someone some time :)

Which Scala framework to use for testing REST services?

I'd like to use Spec2 and Scala to test a REST service that was build using Java. I looked at Spray but it seams like you have to build your application using Spray in order to test it using SprayTest. I also found this thread but it's not really what I'm looking for.
Any other ideas?
We have successfully been testing all of our REST APIs using Specs2 and the Dispatch library (https://dispatchhttp.org/Dispatch.html). Dispatch takes a little bit of time to get your head around, but once you understand how it composes everything together with various operators you can test a simple REST service with a couple of lines of code.
Here's a couple of test cases from out recent project:
def issueErrorStatus = {
val requestBody = "msisdn=447777666666&message=Some test message"
val req = url("http://localhost:%d/otac/issue".format(port)) <<
(requestBody, "application/x-www-form-urlencoded")
val response = Http.when(_ == 400)(req <:< (touchPointHeaders) as_str)
response must_== """{"error":"Message must contain an {OTAC} place holder"}"""
}
def checkOtac = {
val req = url("http://localhost:%d/otac/check".format(port)) <<?
Vector(("msisdn" -> "447777123456"))
val response = Http(req <:< (touchPointHeaders) as_str)
response must_== """{"status":"Present","reissueAllowed":true}"""
}
The first test makes a post request, the second a get request. We also have some more complex tests that parse the response JSON string through the lift-json parser so that we can assert agains the document more easily. The above tests are just checking some simple error/status cases.
There's also a dispatch-reboot project underway that has a simplified API and works with async connections. Not sure how stable it is yet though.
In my last projects I used AsyncHttpClient and Jersey Client for testing REST services and I can recommend both of them. For async operations the former is better (I don't know if jersey client
supports async operations at all).
They are written in Java and have (to my knowledge) no Scala-API.