Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unit testing database code [duplicate]

Possible Duplicate:
Unit testing on code that uses the Database

I am just starting with unit testing and wondering how to unit test methods that are making actual changes to my database. Would the best way be to put them into transactions and then rollback, or are there better approaches to this?

like image 205
user517406 Avatar asked Jun 22 '26 09:06

user517406


2 Answers

If you want proper test coverage, you need two types of tests:

  • Unit-tests which mock all your actual data access. These tests will not acually write to the database, but test the behaviour of the class that does (which methods it calls on other dependencies, etc.)

  • System tests (or integration tests) which check that your database can be accessed and modified. I would considered two types of tests here: simple plain CRUD tests (create / read / update / delete) for each one of your model objects, and more complex system tests for your actual methods, and everything you deem interesting or valuable to test. Good practices here are to have each test starting from an empty (or "ready for the test") database, do its stuff, then check state of the database. Transactions / rollbacks are one good way to achieve this.

like image 104
Guillaume Avatar answered Jun 23 '26 21:06

Guillaume


For unit testing you need to mock or stub the data access code, mostly you have repository interface and you can stub it by creating a concrete repository which stores data in memory, or you could mock it using dynamic mocking framework ..

For system or integration testing, you need to re-create the entire database before each test method in order to maintain a stable state before each test.

like image 42
Mohamed Abed Avatar answered Jun 23 '26 21:06

Mohamed Abed



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!