DEV Community

Discussion on: Need recommendations in Mocking database / Testing Cleanup (Unit Testing)

Collapse
 
dmfay profile image
Dian Fay

Mocking your data is useful if you have a rich domain layer (models with their own suites of functionality above and beyond CRUD), or as rhymes said, if your tests are too slow with real data (which often happens with rich domain layers).

There are better and worse ways to approach populating the database for real, though. You don't want to have each testcase initialize and clean up its own fixture data: if something in your data model changes, you have to correct every single test that touches on it. And teardown is different for each testcase, leading to difficult-to-diagnose issues with data pollution.

Your data model is fundamentally a dependency graph. You can't, for example, have prescriptions without doctors to issue them and patients to whom they're issued. All of your test cases operate on subgraphs of your model: doctors do many other things besides write prescriptions, after all.

The most flexible way I've found to approach fixture data is to compose reproducible datasets. You're testing each functional unit in your data model individually and in combination with other units. So if you have some code which creates a couple of doctors, some code which creates a few patients, and some code which creates some prescriptions linking the previous in various combinations, you can apply as many of those pieces as you need for a given testcase in the before or other setup method. And you can have a single cleanup function which removes every possible record the fixtures could generate. All your fixture code stays in one place and tests consume what they need.