Skip to main content

Exercise 9 (Optional)

Exercise: Creating Unit Tests with dbt-unit-test

Objective

In this exercise, you will create unit tests for the co2_emissions_and_temperatures_by_country model in your DBT project using the dbt-unit-test package. You will mock the dependencies (co2_emissions_by_country and aggregate_country_temperatures) and define the expected results to validate the model's logic.

Essential Reading 📘 Prior to Starting the Exercise

Instructions

  1. Set Up the dbt-unit-test Package:

    • Ensure you have the dbt-unit-test package installed and configured in your DBT project.
  2. Create a New Unit Test File:

    • Navigate to the unit-test directory in your DBT project.
    • Create a new file for your test, for example, test_co2_emissions_and_temperatures.sql.
  3. Write the Unit Test:

    • Open the new file and start framing your unit test using the provided template.
    • Mock the dependencies and provide mock data for co2_emissions_by_country and aggregate_country_temperatures.
    • Specify the expected outcomes for the co2_emissions_and_temperatures_by_country model.

    Example template to start with:

    {{
    config(
    tags=['unit-test']
    )
    }}

    {% call dbt_unit_testing.test('co2_emissions_and_temperatures_by_country', 'assert_co2_emissions_and_temperatures_by_country') %}
    {% call dbt_unit_testing.mock_ref('co2_emissions_by_country') %}
    -- Provide Mock data for co2_emissions_by_country
    {% endcall %}

    {% call dbt_unit_testing.mock_ref('aggregate_country_temperatures') %}
    -- Provide Mock data for aggregate_country_temperatures
    {% endcall %}

    {% call dbt_unit_testing.expect() %}
    -- Provide expected mock data for the test
    {% endcall %}
    {% endcall %}
  4. Implement Mock Data:

    • Inside each mock_ref block, insert the mock data relevant for the respective models.
    • In the expect block, define the expected outcome of the test.
  5. Run the Test:

    • Use the DBT CLI to execute your unit test and validate the functionality of your model.

Tips for Mock Data and Expectations

  • When providing mock data, consider the structure of your source models and the transformations applied in your co2_emissions_and_temperatures_by_country model.
  • Your expected data should reflect the intended output of the model, considering the input mock data.