Issue
I have checked in google and stackoverflow for end to end testing of Spring Boot Rest APIs.
I would like to test controller -> Service -> Repository at once.
I found two approaches are efficient:
1. TestRestTemplate:
Single call to the controller method with in-memory database configuration for repository.
2. MockMvc:
Create 2 Test classes.
one for Controller->Service
and one for Service->Repository.
Is there any way to club both 2 classes into one class.
which is the best way to do "end to end testing" of Spring Boot Rest APIs from above 2 approaches ???
Solution
I would say the better way to do the END2END testing is to use TestRestTemplate. It would actually start-up the server at a random port (it you configured) and call the api itself for testing.In this way, it mimic the actual behavior of the running server and use the default configures and beans.
MockMvc, in my testing experience, is mainly for testing the web layer, aka controllers. I would use mocked Service beans to replace the original ones. So I can test the behaviors of the controller layer itself without having to worry about the bugs in the service layer. More importantly, I don't have to set up any Database before testing.
So I would say, for E2E test, you can go for the first approach.
Answered By - Tianhao Wang