# Unit Testing

Unit testing in dbt allows you to validate your SQL transformation logic using controlled input data. Unlike traditional data tests that verify the quality of existing data, unit tests help you catch logical errors during development, bringing the test-driven development approach to data transformations.

***

### Understanding dbt Unit Tests

Unit tests in dbt help you verify that your transformations produce expected outputs given specific input data. This ensures your business logic is correct before you deploy it to production.

{% hint style="info" %}
Unit testing is available in dbt Core v1.8+ and above
{% endhint %}

***

### Why Unit Testing Matters

Traditional data tests (like `not_null`, `unique`) validate the quality of data that already exists. Unit tests serve a different and complementary purpose:

| Unit Tests                          | Data Tests                       |
| ----------------------------------- | -------------------------------- |
| Validate transformation logic       | Validate data quality            |
| Run before building models          | Run after models are built       |
| Use controlled test data            | Use actual production data       |
| Focus on business logic correctness | Focus on data integrity          |
| Help with test-driven development   | Help with data quality assurance |

Unit tests provide several benefits:

* **Test before building**: Validate logic without materializing models
* **Verify transformations**: Ensure your SQL logic handles edge cases correctly
* **Support test-driven development**: Write tests first, then implement the model
* **Catch errors early**: Find bugs before they reach production
* **Improve code reliability**: Maintain confidence during refactoring

***

### When to Use Unit Tests

Unit tests are particularly valuable when your models include:

* **Complex transformations**: Regular expressions, date calculations, window functions
* **Critical business logic**: Calculations that impact important metrics
* **Known edge cases**: Scenarios that have caused issues in the past
* **Models undergoing refactoring**: Changes to existing transformation logic
* **Frequently used models**: Core models that many others depend on

***

### Unit Test Structure

A dbt unit test consists of three essential parts:

1. **Mock inputs**: Sample data for source tables and referenced models
2. **Model under test**: The model whose logic you want to validate
3. **Expected outputs**: The exact results you expect after transformation

#### Basic Example

Here's a simple unit test defined in YAML:

```yaml
unit_tests:
  - name: test_orders_status_counts
    model: order_status_summary
    given:
      # Define input data for the model's dependencies
      - input: ref('stg_orders')
        rows:
          - {order_id: 1, status: 'completed'}
          - {order_id: 2, status: 'pending'}
          - {order_id: 3, status: 'completed'}
          - {order_id: 4, status: 'shipped'}
    expect:
      # Define expected output data
      rows:
        - {status: 'completed', count: 2}
        - {status: 'pending', count: 1}
        - {status: 'shipped', count: 1}
```

***

### Creating Unit Tests

Unit tests are defined in YAML files within your models directory, typically alongside the model they're testing.

#### Defining Input Data

Mock input data can be provided in several formats:

**Dictionary Format (default)**

```yaml
given:
  - input: ref('stg_customers')
    rows:
      - {customer_id: 1, name: 'John Doe', status: 'active'}
      - {customer_id: 2, name: 'Jane Smith', status: 'inactive'}
```

**CSV Format**

```yaml
given:
  - input: ref('stg_customers')
    format: csv
    rows: |
      customer_id,name,status
      1,"John Doe",active
      2,"Jane Smith",inactive
```

**SQL Format**

```yaml
given:
  - input: ref('stg_customers')
    format: sql
    rows: |
      select 1 as customer_id, 'John Doe' as name, 'active' as status
      union all
      select 2 as customer_id, 'Jane Smith' as name, 'inactive' as status
```

#### Defining Expected Output

You can specify expected outputs in different ways:

**Rows (most common)**

```yaml
expect:
  rows:
    - {customer_id: 1, status: 'active'}
    - {customer_id: 2, status: 'inactive'}
```

**Column Values**

```yaml
expect:
  columns:
    - name: status
      values: ['active', 'inactive']
```

**Row Count**

```yaml
expect:
  row_count: 2
```

### Example: Testing a Customer Classification Model

Let's see a complete example for a model that classifies customers based on spending:

**The model being tested:**

```sql
-- models/customer_segments.sql
SELECT
  customer_id,
  name,
  total_spend,
  CASE
    WHEN total_spend >= 1000 THEN 'high'
    WHEN total_spend >= 500 THEN 'medium'
    ELSE 'low'
  END as spending_segment
FROM {{ ref('stg_customers') }}
```

**The unit test:**

```yaml
# models/customer_segments_tests.yml
unit_tests:
  - name: test_customer_segments_classification
    model: customer_segments
    given:
      - input: ref('stg_customers')
        rows:
          - {customer_id: 1, name: 'Customer A', total_spend: 1200}
          - {customer_id: 2, name: 'Customer B', total_spend: 750} 
          - {customer_id: 3, name: 'Customer C', total_spend: 300}
    expect:
      rows:
        - {customer_id: 1, name: 'Customer A', total_spend: 1200, spending_segment: 'high'}
        - {customer_id: 2, name: 'Customer B', total_spend: 750, spending_segment: 'medium'}
        - {customer_id: 3, name: 'Customer C', total_spend: 300, spending_segment: 'low'}
```

***

### Running Unit Tests

To run unit tests, use the dbt test command with appropriate selectors:

```bash
# Run all unit tests
dbt test --select test_type:unit

# Run unit tests for a specific model
dbt test --select my_model,test_type:unit

# Run a specific unit test
dbt test --select my_specific_unit_test
```

***

### Testing Special Cases

#### Incremental Models

When testing incremental models, you can override the `is_incremental()` macro to test both full refresh and incremental scenarios:

```yaml
unit_tests:
  - name: test_incremental_full_refresh
    model: my_incremental_model
    overrides:
      macros:
        is_incremental: false
    # Test data here...

  - name: test_incremental_update
    model: my_incremental_model
    overrides:
      macros:
        is_incremental: true
    # Test data here including 'this' input...
```

For the incremental update test, you need to provide mock data for the existing table:

```yaml
given:
  - input: this  # Special reference to the current model
    rows:
      - {id: 1, value: 'existing', updated_at: '2023-01-01'}
      - {id: 2, value: 'existing', updated_at: '2023-01-01'}
```

#### Ephemeral Models

To test models that depend on ephemeral models, use SQL format for the input:

```yaml
unit_tests:
  - name: test_model_with_ephemeral_dependency
    model: my_model
    given:
      - input: ref('ephemeral_model')
        format: sql
        rows: |
          select 1 as id, 'test' as name
    # Expected output here...
```

#### Testing Macros

You can override macro implementations for testing:

```yaml
unit_tests:
  - name: test_with_custom_macro
    model: my_model
    overrides:
      macros:
        get_current_timestamp: return('2023-09-15')
    # Test data here...
```

***

### Limitations & Best Practices

dbt's unit testing framework has some limitations to be aware of:

{% hint style="warning" %}

#### Current Limitations

* Only supports SQL models (not Python models)
* Can only test models in your current project
* Doesn't support materialized views
* Doesn't support recursive SQL or introspective queries
* Requires all table names to be aliased in join logic {% endhint %}

#### Best Practices for Effective Unit Testing

| Practice                      | Description                                                      |
| ----------------------------- | ---------------------------------------------------------------- |
| Focus on logic, not functions | Test your business logic rather than built-in database functions |
| Use descriptive test names    | Clearly explain what each test is verifying                      |
| Test edge cases               | Include unusual scenarios your logic needs to handle             |
| Only mock what's needed       | Define only the columns relevant to your test                    |
| Run in development            | Use unit tests during development, not in production             |
| Use in CI/CD                  | Integrate unit tests into your CI/CD pipeline                    |

***

### Test-Driven Development with dbt

Unit tests enable a test-driven development (TDD) workflow for your data transformations:

1. **Write a test**: Define the expected behavior
2. **Run the test**: It should fail because the model doesn't exist or doesn't handle the case yet
3. **Implement the model**: Create or modify the model to pass the test
4. **Verify**: Run the test again to confirm it passes
5. **Refactor**: Clean up your implementation while keeping the tests passing

This approach helps ensure your models correctly implement business requirements from the start.

By adopting unit testing in your dbt workflow, you can catch issues earlier, document model behavior, and build more confidence in your data transformations.
