I'm currently developing a Spring-based web-application, in which almost every operation create/update/delete something in the database. The logic mostly about checking condition so as to we should create/update records in the database or not.The reason I want to try unit test is that we often meets regression errors when request changes or refactor. Most the bugs comes from Database changes, when I doesn't fully reflect those changes in the code. I have some experience in web-development now, but it seems that's not enough to stop them appear.My controller/service is actually not too complex. I just take the binding object submited from the HttpRequest, check the condition & record in DB. Sometimes the system must read the Database, take out some records & manipulate them, then update some other records.Much of the coding effort lies on the interface(HTML/CSS/Javascript) too.I'm investigating unit test, and I heard that when it comes to database operation, it's no longer unit test, since the test will be slow. Is that true? So that if my project is heavily database-operation, I shouldn't use unit test?I also heard about DBUnit & some in-memory database which can quicken the test. Should I use them? And how I can write good unit test for database operation?
Write Unit test for heavily-database application?
java;unit testing;spring
You probably should have unit tests and integration tests. In the unit tests, you test for example your controllers/services in isolation. To achieve that, you may use for example a mocking framework such as Easymock or Mockito to cut the dependency to the database.Your integration tests should go the whole way, from your controllers/services right to the database. You can write your integration tests with the same basic framework as your integration tests (JUnit or TestNG to name the most popular). I personally like DBUnit to prepopulate a database and verify the database state after the test. Whether you use an in-memory database IMO strongly depends on your persistence layer. If you use for example a JPA framework that generates its own queries, I like having an in-memory db. If you write your own SQL-Queries, it can be more difficult to use another DB than your production target as you cannot be sure that the syntax is gonna be equivalent, so an integration test against e.g. an in-memory H2 database not necessarily means that the Syntax works with DB2. This becomes even more problematic if you use stored procedures.A good integration test itself runs in isolation, meaning that you should set up the database before each test to avoid dependency among tests. You don't want the success of your tests depend on the order they are executed in. After you perform your operations, you should use some kind of assertions to test if the database state is conforming to your expectations. DBUnit for example has its own asserts for comparing Datasets or Tables. 