Skip to content
SilverNEW 5 min read · dbt 1.8 · Tests

Unit tests

Data tests check the rows you built today; they cannot tell you whether your logic handles cases that are not in today's data. Unit tests feed a model small hand-written inputs and check its output. This lesson shows how to write them.

Pipelines in production · dbt · Silver · Testing logic, lesson 1 of 1

Read first: Data tests (skip if you know it)

In plain words first

Before serving a new recipe, a chef cooks it with a few measured ingredients, including the awkward ones (no salt, double butter), and tastes the result. They are testing the recipe, not today's delivery.

A dbt unit test does that: fixed input rows in, expected rows out, whatever the real data looks like today.

Logic, not data

A data testdata test: A query that looks for bad rows, such as nulls, duplicates or broken relationships. The test fails if it returns any row. Learn more → checks the rows that were built: "invoice_id is unique today". It cannot tell you whether the modelmodel: A SELECT statement in a .sql file. dbt runs it and saves the result in the warehouse as a table or view named after the file. Learn more →'s logic is right for cases that are not in today's data, like an account that never played a song or two plays at the same second. A unit test runs the model on small, fixed input rows you write, and compares the result to rows you expect. It is a test of the SQL, not of the data.

Data testUnit test
ChecksThe built tableThe model's logic on fixed inputs
RunsAfter the model buildsBefore it builds; the model is not materializedmaterialization: How dbt stores a model: as a view, a table, an incremental table that only adds new rows, or ephemeral (inlined, not stored). Learn more →
InputReal dataRows written in YAML (or CSV)
CatchesBad or unexpected sourcesource: A raw table loaded by another tool, declared in YAML so models can select from it with source() and dbt can test it and check its freshness. Learn more → dataWrong joins, edge cases, regressions when refactoring

Writing one

YAML · models/marts/_marts__unit_tests.yml
unit_tests:
  - name: dim_accounts_keeps_accounts_without_plays
    description: Accounts that never played get 0, not null, and are kept.
    model: dim_accounts
    given:
      - input: ref('stg_accounts')
        rows:
          - {account_id: 1, plan_code: premium}
          - {account_id: 2, plan_code: free}
      - input: ref('stg_plays')
        rows:
          - {play_id: 10, account_id: 1, track_id: 7, played_at: "2025-01-05 08:00:00"}
          - {play_id: 11, account_id: 1, track_id: 7, played_at: "2025-01-06 09:30:00"}
    expect:
      rows:
        - {account_id: 1, total_plays: 2, distinct_tracks: 1}
        - {account_id: 2, total_plays: 0, distinct_tracks: 0}
  • Every ref() or source() the model reads needs a given input (an empty one is rows: []).
  • You only list the columns that matter: missing input columns are filled with null, and only the columns in expect are compared.
  • dbt replaces each ref with your rows as a CTE, runs the model's SQL and diffs the result. Row order does not matter.
Shell
dbt test --select "dim_accounts,test_type:unit"   # run one model's unit tests
# unit tests run first; the model builds only if they pass
dbt build --select dim_accounts

Testing an incremental model

An incremental modelincremental model: A model that, after its first build, only processes new or changed rows and merges them into the existing table. Learn more → has two code paths. Test the incremental one by overriding is_incremental() and giving rows for this, the existing table:

YAML · models/marts/_marts__unit_tests.yml · expect is the batch the model selects, not the final table
unit_tests:
  - name: fct_plays_only_loads_newer_plays
    model: fct_plays
    overrides:
      macros:
        is_incremental: true
    given:
      - input: ref('stg_plays')
        rows:
          - {play_id: 1, played_at: "2025-03-01 10:00:00"}
          - {play_id: 2, played_at: "2025-03-02 09:00:00"}
      - input: this
        rows:
          - {play_id: 1, played_at: "2025-03-01 10:00:00"}
    expect:
      rows:
        - {play_id: 2, played_at: "2025-03-02 09:00:00"}

What to unit test

  1. 1
    Edge cases that real data rarely has today: nulls, ties, zero, empty inputs, a play exactly at midnight.
  2. 2
    Tricky logic: regex parsing, date arithmetic, window functionswindow function: A function that computes a value for each row from a group of related rows (its window), without collapsing them like groupBy does. Learn more →, case statements with many branches.
  3. 3
    Bugs you have fixed, so they stay fixed.
  4. 4
    Models you are about to refactor: write the tests first, then change the SQL.
Tip: Unit tests need the warehousewarehouse: A database built for analytics on large tables, like Snowflake, BigQuery, Databricks or Redshift. dbt runs its SQL there. Learn more → to run (the SQL executes there, on tiny inputs), so run them in development and CI. Exclude them from production jobs with --exclude-resource-type unit_test: the logic has not changed since CI, and production should spend time on data tests.

Common mistakes

  • Expecting unit tests to catch bad source data — They use your rows, not real ones. That is what data tests are for.
  • Forgetting an input — Every ref and source the model reads needs a given entry, or the test fails to compile.
  • Running unit tests in every production job — They test code, which only changes in pull requests. Run them in CI.

Key takeaways

  • Unit tests check a model's logic on fixed inputs; data tests check the built data.
  • given lists rows for every ref and source; expect lists only the columns that matter.
  • Override is_incremental and give rows for this to test the incremental path.
  • Run unit tests in CI, not in every production job.

Interview prep

THE QUESTION

"What is the difference between a dbt unit test and a data test?"

A data test queries the built table for rows that break a rule, so it checks the data, every run. A unit test (dbt 1.8+) runs the model's SQL on small input rows defined in YAML, before the model is built, and compares the output to expected rows, so it checks the logic, including edge cases that real data does not contain yet. Unit tests belong in development and CI; data tests run in every production build.

Avoid: "unit tests and data tests are the same thing in YAML". One checks logic on fixed inputs, the other checks built data.

Follow-ups · answer out loud, then open

Follow-up"Do you have to list every column of every input?"
No. Unlisted input columns are null, and only the columns listed in expect are compared, which keeps tests small and focused on the case.
Scenario"You are about to rewrite a complicated mart for performance. How do you make sure results do not change?"
Write unit tests for its edge cases first, against the current SQL, then refactor until they pass. Also compare the old and new tables on real data (for example with an audit query or the audit_helper package) before switching.
Trap"Run unit tests in every production run to be safe."
The logic only changes in pull requests, so CI is where they belong. Production runs use --exclude-resource-type unit_test and spend their time on data tests.

Check yourself

3 questions

When does a unit test run in dbt build?

Show the answer

Before the model is built. It tests the logic first; the model builds only if it passes.

An input column is not listed in a given row. What value does it get?

Show the answer

null. Unlisted columns are filled with null.

How do you test the incremental branch of a model?

Show the answer

Override the is_incremental macro to true and give rows for this. The override makes the incremental filter active; this supplies the existing table.

Keep going

Up next · new module: Production incrementals · 6 min read
Incremental strategies
append, merge, delete+insert, insert_overwrite and microbatch: what each runs and which one fits.

Related lessons

Previous: Snapshots (SCD Type 2)

Primary sources: Unit tests · Unit test properties