user404345
user404345

Reputation:

How to test a spray service

Looking through the docs it seems to be accepted practice that spray routes should be defined in a trait e.g.

trait MyService extends HttpService {
    val route = ...
}

There are some good integration test examples using the Specs2RouteTest but they all seem to fire off a request and perform assertions on the response. But how would I verify that the route is talking to the other collaborators as it should? As I understand it, I can't pass the collaborators in through a constructor as I'm testing a trait

Upvotes: 2

Views: 83

Answers (1)

yǝsʞǝla
yǝsʞǝla

Reputation: 16412

You can pass these collaborators as trait fields instead. You can also use some service locator mechanism you prefer - something that looks up you service.

Essentially your question is about dependency injection DI and maybe mocking those dependencies in test.

My approach with Spray was to use Cake pattern to have those dependencies defined as trait fields and when you put your cake together the last layer overrides/provides those dependencies.

Take a look a this example: https://github.com/izmailoff/Spray_Mongo_REST_service

This is a test that uses that cake: https://github.com/izmailoff/Spray_Mongo_REST_service/blob/master/rest/src/test/scala/com/example/service/GetTweetSpec.scala

And this is the helper class that puts together that cake with mocked DB for the test: https://github.com/izmailoff/Spray_Mongo_REST_service/blob/master/rest/src/test/scala/com/example/test/utils/db/ServiceTestContext.scala

Here are the non-test/prod files that put the cake together: https://github.com/izmailoff/Spray_Mongo_REST_service/tree/master/rest/src/main/scala/com/example/service

Especially: https://github.com/izmailoff/Spray_Mongo_REST_service/blob/master/rest/src/main/scala/com/example/service/RestServiceHandler.scala

It might need some cleanup but you can grasp the idea.

Upvotes: 1

Related Questions