Testing objects that come from a database

svdsinner

Ars Legatus Legionis
15,152
Subscriptor
If I have an application that uses a database as its data store (and ultimate source of truth) that brings some obvious issues when developing tests:
  • In the applications, objects should ONLY be hydrated from the database (except new ones about to be inserted into the database)
  • In testing, objects should be created from test-specific data and not from the database
  • In the applications, object behaviors alter the underlying database
  • In testing, object behaviors should NEVER alter the underlying database
  • Etcetera, etcetera

There are numerous ways to handle this with many names like mocking, stubbing, doubling, etc. Many holy wars are fought on what is the "correct" way to handle this.

Ultimately, I want a framework that works equally well in testing and in the application, that requires the least effort to use.

Assumptions/Criteria:
  • Team doesn't care if one error breaks many tests. (IOW, there is no need to write the tests so that the failed test specifically pinpoints where the error is.)
  • Use real objects if possible and a double/stub/mock if it's awkward to use the real thing. The database is the main component that needs to be faked in testing, since it makes no sense to have tests altering real production data in the database.
  • Test code should look as similar to real code as possible.

What have patterns have you guys used that makes switching between the real application and the tests the simplest and cleanest? Where in the process do you substitute fake test objects for the real ones? Which method sucks the least in practice?
Example: Have the database and the fake test database share a data access layer interface. In the application use an implementation of the interface that uses the database, and in test code use an implementation that uses test data.
 

ramases

Ars Tribunus Angusticlavius
9,024
Subscriptor++
For unit tests, mock the DAL and use it to return test fixtures, or to assert expected calls made to the DAL.

For integration tests, your tests most definitely should execute real queries against a real database (unless you only ever use entirely ORM-generated queries, you also need to test your queries), and if the functionality under test would be expected to modify state in the database, it most definitely should be allowed to alter the underlying database. Integration tests should always strive to reduce the difference in runtime environment between test and production as much as reasonably possible.

There are several strategies for integrating the creation of disposable test databases directly into the build process, for example via in-memory databases with SQL dialect emulation like hsqldb, or a dockerized postgresql/mysql database, and supply it with test fixtures. That way, you simply need to supply your application a test configuration with an appropriate connect string and username/password, and presto, you can run your real DAL against your disposable test database. If a test dirties the database, you simply truncate all the tables and reload the fixtures.

Every worthwhile framework has support for that these days.
 

svdsinner

Ars Legatus Legionis
15,152
Subscriptor
For integration tests, your tests most definitely should execute real queries against a real database (unless you only ever use entirely ORM-generated queries, you also need to test your queries), and if the functionality under test would be expected to modify state in the database, it most definitely should be allowed to alter the underlying database.
Practical question. We would have a specific non-prod database to pound these type of tests against. Where is a good real world place in the testing process to force the database into a testable state? (IOW, Make the database valid by reloading from scratch or whatever and removing any destruction that previous failed test may have wrought on the database.)
Manually on demand?
Automatically at the start of every test run? (One big reload at the beginning of all test)
Automatically, bit by bit before each test? (Fix whatever is needed for just the upcoming test to run)
Automatically after a failed test run?

What are opinions on how often tests that actually exercise the database should be run? They are too time intensive to run on every code check-in. I'm guessing doing them as part of a nightly build would be sufficient? Or just manually before development milestones that deserve extra testing?

(Again, I don't give a @#$^ about religiously following a specific testing methodology. I just want useful tests for our small team that smoke out errors early and don't waste development time writing numerous nearly meaningless tests.)
 

minnmass

Ars Tribunus Militum
2,087
Subscriptor
Practical question. We would have a specific non-prod database to pound these type of tests against. Where is a good real world place in the testing process to force the database into a testable state? (IOW, Make the database valid by reloading from scratch or whatever and removing any destruction that previous failed test may have wrought on the database.)
Manually on demand?
Automatically at the start of every test run? (One big reload at the beginning of all test)
Automatically, bit by bit before each test? (Fix whatever is needed for just the upcoming test to run)
Automatically after a failed test run?

My vote is "at the start of every test run".

I have had good experiences verifying that the data store is in a reasonable state before starting individual integration tests. Tests will then fail early if the data doesn't look right (presumably because some other test failed to clean up after itself, possibly after it itself failed) and the data store is likely in the state that generated the initial failure. That latter bit can be important when figuring out what went wrong.

Eg.: if you're working on the software for an ATM and testing the "withdraw money" happy path, assert that the account and the ATM have enough money to handle the withdrawal then run the withdrawal and assert that the account and ATM's initial store have been reduced as expected. If the account's empty when the test starts, it's clear that something has gone wrong, so stop the test early and hope that the test that put the data store in the "wrong" state also failed.

As a dev, I hate bugs like "I did X and Y didn't happen, so I undid X; please fix X". Don't undo X: undoing X just means that - best case - we both waste time un/re-doing X; worst-case, it means that whatever you did to undo X means that when I do X I won't see the problem you did and we have to go back and forth a million times before landing on "cannot reproduce, probably transient issue". Obviously, if there's an automated process in place, that puts a window on when the dev can look at the data store to see its state. If that process is per-individual-test, they're never going to see the bad state.

What are opinions on how often tests that actually exercise the database should be run? They are too time intensive to run on every code check-in. I'm guessing doing them as part of a nightly build would be sufficient? Or just manually before development milestones that deserve extra testing?

... depends on your release cadence. If you're releasing daily, the tests should probably be run on every check-in. If you're releasing weekly or less often, it's probably okay to run nightly (maybe even just twice a week, at least automatically).

We have several dev teams working on the same app. For reasons, each team has a stage branch that the team members merge their individual work to. For releases, we merge one of those stage branches into master, run through pre-prod testing, then deploy to production. In that scenario, I'd want to run the tests on the stage branches at least once before they could get merged to master, ideally as part of the flow/deploy automation that merges the stage branch to master.
 

Ardax

Ars Legatus Legionis
19,795
Subscriptor
Where is a good real world place in the testing process to force the database into a testable state?
It depends on the amount of time it takes to spin up the test DB, but "at the beginning of each test run" should be good enough. As long as you can easily see which test failed first when you've got cascading failures, it won't be too painful.

Our SQL integration tests actually just start a transaction and roll it back after every test.

We use an in memory DB as much as we can and those tend to start with an empty DB with each individual test (or sometimes a group of them) setting up its own preconditions.
 
D

Deleted member 43669

Guest
Many web frameworks provide support for this. Django does ( https://docs.djangoproject.com/en/3.2/t ... ontestcase ), Spring also has some stuff ( https://docs.spring.io/spring-framework ... n-rollback ). For Django I've also used a few methods to have database fixtures.

I'd check first what your web framework provides, or if there exist related libraries.

I just mentiond this https://testing.googleblog.com/2014/05/ ... sting.html at work this week- it's always my first suggestion when deciding how to test stuff. Write first the tests that address your biggest worries... and do not adhere necessarily to any testing school dogma... just make sure that you have short enough feedback cycles...
 

gregatron5

Ars Legatus Legionis
13,009
Subscriptor++
As to most questions, I think the answer is “it depends.”

How heavy is your database? If it’s relatively lightweight, you may be able to use an in-memory database that emulates your real one. You might be able to use testContainers and spin up what you need on demand. You might be able to use a single transaction as already suggested. (Sometimes, though, an IT requires multiple transactions, which would rule that out.) If it’s more of a beast you might need to have a “test” database and constantly reset it, either with snapshots or some manual steps.

As for setting up data in the DB, whether you use raw SQL (or similar) to setup a “known state” or whether you use the application itself to seed data is up to you. The amount of work to do one or the other is highly application dependent. Where I am now we use both strategies, and we have a test framework that will populate targeted portions of the database with real-ish data.
 
Our SQL integration tests actually just start a transaction and roll it back after every test.
That works for simple interaction.

You generally don't want to [explicitly] commit (or rollback) a transaction within a stored procedure - that makes it difficult to reuse the procedure elsewhere if your transaction semantics differ. Implicit commits happen on INSERT/UPDATE/DELETE. If OP is not using stored procedures, typically ad hoc queries do not get their query plan cached (performance gain for being able to do a soft parse, rather than hard parse all the time).

My suggestion to the OP is for an ephemeral database, containerized.
  1. Test suite creates the database, the schema (tables, etc)
  2. OPTIONAL: Run DDL script to update the database to the version/changes for the current release, in case you need to support customers running previous version(s)
  3. Run data load scripts for basic infrastructure - code/dimension tables, etc
  4. Run test specific data load scripts
  5. Run appropriate test(s) - integration, unit...
  6. Run data cleanup script(s) - "TRUNCATE TABLE <tableName>" will drop all records in the specified table; use DELETE ... for more specific record removal
  7. OPTIONAL: script resetting automated numeric primary key value(s)
  8. Repeat steps 4-7 for test(s)

Convention for primary keys is that you do NOT expose them to end users.