I'm trying to figure out what is the best approch to unittesting in SpringBoot app. Before last friday i thought that best approach is to test:
- controllers with mockmvc and mocked services
- services with mocked repositories
- repositories with mocked db
- using
SpringBootTestmainly for integration tests.
But then i watched this -Ian Cooper - TDD, Where Did It All Go Wrong and I've realized that my testswas implementation tests, and I should only mock db, filesystem, other systems, not my application.
And I'am wondering how should I be doing this? Because when I will be creating all objects myself it will still be "testing implementation", so I can use SpringBootTest with MockBean but this would be extremly slow.
Can someone clever than me could share his experience or thougths on this?
CodePudding user response:
If you are trying to write tests for already written codebase, I would start it with integration tests. Also, mocking a DB with an in memory H2 DB gives executing test suits and clearing data for the next one, or even keeping the data persist for couple of tests that are interrelated and then delete.
Spring has been designed around dependency injection, so use it to test your services while mocking other repositories(possibly JPA). Nowadays JPA comes down to minimum cruds so leave it to the last as you want to focus on business logic tests.
CodePudding user response:
I would suggest the following:
Use a different application.properties in src/test/resources with an embedded H2 database.
Seed the H2 DB with data.sql also in your src/test/resources, which will be automatically picked up.
Use MockMVC to simulate the http client.
Everything else should be as production.
i.e. use the principle of Inversion of Control (IOC) by plugging in a test DB using test only configuration.
