1

This question is next to the question I had asked here. In this question I want to focus on ways of testing a Spring based REST Controller.

Currently, the way I have set-up my testing is - Use spring-test-mvc framework with database that basically does end-to-end testing.

I want to get rid of a database layer. Why? Do I really need a database layer? Can't I mock a database?

So, I would like to know of an efficient way of testing a Spring based REST Controller which incorporates framework like Mockito, etc.

Please share and guide me in the right direction.

Community
  • 1
  • 1
jsf
  • 2,851
  • 9
  • 30
  • 33
  • Mock (or stub/fake) your services. – Dave Newton Feb 06 '12 at 19:22
  • So, what you are saying is - we can replace the database layer by mocking Services. And it's a good practice? Is it safe in terms of complete and guaranteed testing? – jsf Feb 06 '12 at 19:24
  • 1
    Is as complete and guaranteed as you make it--controllers should talk to services, services should talk to the DB. If you're testing your controllers, you only need to mock/stub service interactions. – Dave Newton Feb 06 '12 at 19:41
  • 1
    @DaveNewton - if you write those two comments as an answer, I will upvote it. – Dawood ibn Kareem Feb 07 '12 at 08:09
  • @DavidWallace Done, and expanded--hopefully not too much, and not worse than my terse comments :) – Dave Newton Feb 07 '12 at 15:58

1 Answers1

4

Generally, controllers only interact with services. Most controller/service interactions are data and/or status marshalling. (And exception handling.) Mocking/stubbing (stucking?) the service layer allows us to ensure the controller handles anything that might happen between it and its services.

"Complete and guaranteed" is up to you. For example, a service that interacts with a User database will probably only do a few things: retrieve a user, retrieve a list of users, update a user, or throw an application- or framework-specific exception. From the controller's point of view, those are the things that need to be tested--that's not that much stuff, so "completeness" is fairly straight-forward.

None of that tests the services or DAOs. Services, for example, might be tested using "stucked" DAOs. DAOs might be tested with an in-memory DB (although to be honest, I don't always test DAOs unless they have non-trivial, developer-generated SQL).

None of that is a replacement for integration testing, which can test routing, error and exceptional-condition handling, data formatting and content, and so on.

Dave Newton
  • 158,873
  • 26
  • 254
  • 302