Introduction
I recently worked on a migration from good-old servlets web-services project to a REST using Spring MVC. The main motivation for the migration was testability. Servlets made very hard to create a good test suite, not good enough for continious integration. On the other hand Spring MVC not only makes testing posible but enjoyable. I’ll briefly layout my strategy and learnings from that project.
Step 1: Create High-level Http tests
This step wil save you a lot of time in the long run. They will serve as a verification step. For these tests I used RestAssured. It lets you test web-services from the client’s perspective. jsonPath makes it easy to verify responses.
Step 2: Transform Servlets to Controllers
Step 2a: Create a one Cotroller per Servlet
Copy and paste the content of get and post### In this step pass the HttpSevletRequest and HttpServletResponse as parameters
1 2 3 4 5 6 7 8 9 10 |
|
Becomes
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
|
Step 2b: Replace Dependencies to HttpServletRequest
Pass the parameter types specific to your service. This:
1 2 3 4 5 6 7 8 9 10 11 12 |
|
Becomes:
1 2 3 4 5 6 7 8 9 10 |
|
Step 2c: Create appropriate return types and remove dependency to HttpServletResponse
Split Methods and return the appropriate Object Types
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
|
Becomes:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
|
Step 3: Create Unit Test for Controllers
Use @RunWithSpring
Step 4: Integrate Security
Step 5: Create Integration Tests
Use MockMvc