ForCRUD
operations of various databases, corresponding unit tests must be written. There are not many problems with searching, but there will be problems with additions, deletions, and modifications. Since the code is running in a production environment, it cannot really be changed.
Now what I think of is that the solution is to create another database for development data separate from the database in the production environment, but this is a bit troublesome.In the real development process of an enterprise, how are unit tests for codes that need to be modified to the database generally done?
Ibrieflylooked at the introduction ofmockito
, but I didn’t seem to find a good solution. Can anyone give any suggestions or recommend information in this area?
Note:
I saw this introduction to unit testing in the IBM community:
Unit tests should be easy to execute. The execution of unit tests should not require cumbersome operations such as configuration to run. If the unit test code includes access to databases, networks, etc., the test is not a true unit test.
One theory is thatunit testing is not allowed to connect to the real database, so all database operations must be mock
, so how should the database part of the code be tested?
Unit testing can be done using h2. Generally, enterprise-level development has its own testing environment, and it is not a big problem to directly test the database
This is not a unit test, but an integration test
You should not use in-memory databases such as h2, because the syntax and features of these databases are different from your production database, which may cause test failure
If you use Spring, please refer to the chapter about Integration Test in the official Spring documentation
Use an in-memory database to solve this problem. After introducing the in-memory database, you need to manage the ddl script and the necessary initialization data dml script in the code.
Start the in-memory database every time you run a unit test, flash the ddl and dml scripts, and then execute the unit test logic. The recommended management database script tools include flyway and liquibase