iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
📖

Backend Practicalities: Managing Test Data and Table Verification Effectively

に公開

Introduction

In this article, I will summarize three common scenarios that often occur in backend development:

  • Using an ORM to insert data for unit tests
  • Using SQL to insert data for validation environment scenario tests
  • Writing a large amount of SQL to verify production data

Rather than the implementation itself, I will organize why creating test data and verifying tables takes time in a way that is easy to manage in the field. In backend development, maintaining high turnover rates for validation is crucial to improve quality while moving forward.

Why We Use Different Insertion Methods for Unit Tests and Validation Environment Scenario Tests

Even though both are "test data insertion," the objectives differ between unit tests and validation environment scenario tests.

  • Unit tests: I want to quickly confirm the correctness of logic units.
  • Validation environment scenario tests: I want to run the application in QA or Staging environments and confirm that the execution results, including the database, are as expected.

Because of this difference, these insertion methods are often separated in the field.

Use ORMs to Insert Minimal Data for Unit Tests

For unit tests, it is easier to maintain if you create only the minimum data required for the target logic using an ORM. This makes it easier to keep up with model changes and makes the test code easier to read and understand.

For example, the following policy is adopted:

  • One purpose per test
  • Standardize insertion using Factory or Fixture functions
  • Fix volatile values such as timestamps

Use SQL to Insert Data for Validation Environment Scenario Tests

Validation environment scenario tests in this context assume an environment where the application and database are actually running, such as QA or Staging, rather than a local environment.

In validation environment scenario tests, it is often more stable to insert test data directly using SQL. The reason is that you can explicitly create a table state that is close to actual operations.

SQL insertion is particularly effective in the following cases:

  • You want to create dependencies across multiple tables all at once
  • You want to reproduce scenarios including the impact of constraints and triggers
  • The order of insertion is difficult to see when going through an ORM
BEGIN;

INSERT INTO users (id, name, status) VALUES
  (1001, 'test_user_a', 'active'),
  (1002, 'test_user_b', 'inactive');

INSERT INTO orders (id, user_id, total_amount, status) VALUES
  (5001, 1001, 12000, 'created'),
  (5002, 1001,  3000, 'created');

INSERT INTO order_items (id, order_id, sku, quantity) VALUES
  (9001, 5001, 'A-001', 2),
  (9002, 5001, 'B-001', 1),
  (9003, 5002, 'C-001', 1);

COMMIT;

Create Data via the UI Whenever Possible

Among your test data, it is safer to first create data that can be generated through the regular business application UI. This is because it ensures you go through the actual operational paths, such as input validation, default value settings, and save processing for related tables.

It is easier to manage if you use different approaches as follows:

  • Data that can be created via UI: Create via UI
  • Data that cannot be created via UI: Supplement with SQL or batch jobs
  • Large volumes of data or exception patterns: Bulk insert via SQL

In validation environment scenario tests, it is common practice to first create a single instance via the UI to confirm the expected save results, and then use SQL to increase the required volume.

On the other hand, some data used for monitoring or judging states can be difficult to reproduce through the UI. This is because the generation conditions may be complex, or the data may not exist in production depending on the time of year. In such cases, it is practical to explicitly create the necessary prerequisites for validation using SQL. This is especially true for workflow-related features where creating specific states like "waiting for approval," "remanded," "re-applied," or "expired" via manual UI operations tends to be tedious. When you want to test multiple patterns of such states, creating them directly via SQL makes it easier to increase the turnover rate of your validations.

For example, it is easier to operate if you follow this logic:

  • Data reproducible through the standard flow: Create via UI
  • Data with strict reproduction conditions: Create minimal configurations via SQL
  • Periods when no corresponding data exists in production: Supplement with validation data via SQL

Additionally, for test data that is time-consuming to create or for cases where you perform the same validation iteration multiple times, it is more efficient to create it via SQL from the start. Rather than repeating UI operations every time, slightly modifying the SQL and re-executing it makes it easier to increase the number of trials and stabilizes validation speed.

Decision Flow for Test Data Insertion Methods

In the field, following this order helps avoid confusion when making decisions:

  1. Can it be created without issues via the business UI?
  2. Is the volume large, making manual UI operation time-consuming?
  3. Is it necessary to create exception patterns or conditions that are difficult to reproduce?
  4. Do you need to explicitly reproduce the table state, including constraints and triggers?

If 1 is YES, create it via the UI. If any of 2 through 4 are YES, prioritize SQL insertion.

Why We Write Extensive Verification SQL for Validation Environment Scenario Tests

In validation environment scenario tests, it is not uncommon for the verification SQL to be longer than the implementation SQL. This is because multiple perspectives are required to prove that nothing is broken.

Here are four types of verification SQL frequently used in practice:

  • Count verification: Does it match the expected number of records?
  • Diff verification: Which columns changed before and after the update?
  • Consistency verification: Foreign keys, parent-child relationships, and existence of duplicates.
  • Exclusion verification: Is the data that should not have been touched left unchanged?
-- Was only the target order updated?
SELECT id, status, updated_at
FROM orders
WHERE id IN (5001, 5002)
ORDER BY id;

-- Was any non-target order updated?
SELECT id, updated_at
FROM orders
WHERE id NOT IN (5001, 5002)
  AND updated_at >= '2026-02-21 09:00:00';

-- Consistency of line item counts
SELECT o.id, COUNT(oi.id) AS item_count
FROM orders o
LEFT JOIN order_items oi ON oi.order_id = o.id
WHERE o.id IN (5001, 5002)
GROUP BY o.id
ORDER BY o.id;

It Is Normal for SQL Verification and Investigation to Take Longer Than Implementation

In the field, moving your hands for the following tasks takes more time than you might imagine:

  • Test data creation
  • Validation of scenario tests in the environment
  • Investigation of production data
  • Incident investigation
  • Tracking differences in historical data
  • Recalculation of aggregates
  • Temporary verification queries

Since none of these can proceed without writing SQL, it is common for the time spent chasing target data with SQL to exceed the time spent writing application code.

Relying on DB State as the Final Source of Truth

Sometimes, application implementation or logs alone cannot pinpoint where a discrepancy occurred. Ultimately, the process leads to directly checking the DB state and establishing facts with SQL.

In practice, you will often hear phrases like these:

  • The DB state is the final source of truth.
  • Look at the data before looking at the specifications.
  • If it doesn't work, trace it with SQL first.

Typical Patterns Where Investigation SQL Becomes Long

Verification SQL expands because the subject of the investigation is rarely simple:

  1. Production data is not clean.
  2. There are more branches than in the test data.
  3. It is necessary to verify that non-target data is unaffected.
  4. Tables joined tend to increase.

In particular, when NULLs, duplicates, manual updates, and exception records are mixed in, simply separating the conditions causes the SQL to lengthen.

Key Points That Make Production Data Verification Time-Consuming

What makes production verification difficult is that, unlike in test environments, you must assume the data is "dirty." You have to deal with mixtures of NULLs, duplicates, stale statuses, and traces of manual updates.

Therefore, following this sequence prevents you from getting stuck:

  1. Fix the target period and target IDs first.
  2. Align the population with count verification SQL.
  3. Pick a few representative records and verify them at the column level.
  4. Verify that non-target data remains unaffected.
  5. Match the handling of anomalous values against the specifications.

Summary

In backend practice, it is realistic to proceed by using ORMs for unit tests, SQL for validation environment scenario tests, and fixed-perspective verification SQL for production data checks. Especially in backend development, since the speed of validation turnover is directly linked to quality and development speed, choosing an insertion method that allows for rapid state reproduction is crucial. A significant portion of backend SQL work is not just implementation, but verification and investigation. This is not wasted effort; it is an essential process for ensuring quality.

Discussion