Introduction to Common Test with Erlang

March 20, 2025

Testing is a fundamental part of software development, ensuring that applications function correctly, remain stable over time, and meet their expected requirements.

Erlang, known for its concurrency and reliability, powers many large-scale, highly available applications, from telecom systems to financial platforms. Given its distributed nature and the need for high uptime, rigorous testing is essential to prevent failures and ensure smooth operation.

This is where Common Test comes in. As a powerful testing framework built into Erlang/OTP, Common Test is designed for automated testing of complex systems, supporting unit tests, integration tests, and system-wide testing. With features like structured test suites, logging, parallel execution, and built-in reporting, it is widely used for validating Erlang applications in production environments.

The goal of this post is to introduce Common Test, explain its core concepts, and guide you through setting it up and writing your first test suite. By the end, you’ll have a solid understanding of how to leverage Common Test to improve the reliability and maintainability of your Erlang applications.

 

What is Common Test?

Common Test is a powerful automated testing framework designed specifically for Erlang/OTP applications. It provides a structured way to write and execute test cases, ensuring that Erlang-based systems remain reliable and function as expected.

 

Origins and adoption

Common Test is a core component of Erlang/OTP, originally developed to support telecommunications and distributed systems — domains where high availability and fault tolerance are critical. Over time, its capabilities have made it a popular choice beyond telecom, with adoption in fintech, cloud infrastructure, and large-scale distributed systems.

 

Key use cases

Common Test is versatile and supports multiple types of testing, including:

  • Unit testing: Verifying individual functions and modules.
  • Integration testing: Ensuring different components of a system work together.
  • System testing: Validating the behavior of an entire system under real-world conditions.

With built-in logging, reporting, parallel execution, and support for distributed testing, Common Test is a robust framework suited for testing complex, fault-tolerant applications running on the BEAM VM. In the next sections, we’ll explore how to set up Common Test and write effective test suites for Erlang projects.

 

Setting Up Common test

Before writing and running tests with Common Test, you need to ensure that your Erlang environment is set up properly. Since Common Test is part of Erlang/OTP, it is included by default, making installation straightforward.

 

Installing Common Test

If you have Erlang/OTP installed, you already have Common Test. You can verify its availability by running:

erl -eval 'io:format("~p~n [code:lib_dir(common_test)]).' -s init stop

If Common Test is installed, this command will return the directory path where it is located.

 

Setting up a basic Common Test Suite

Create a new directory for your test suite

mkdir -p test && cd test

 

Generate a test suite template
Run the following command inside your Erlang project directory:

ct_run -make

This generates a test/ directory with the necessary structure for Common Test.

 

Define a test module
Create a test suite file (e.g., example_SUITE.erl) inside the test/ directory:

-module(example_SUITE).
-compile(export_all).

-include_lib("common_test/include/ct.hrl").

% Define the test suite
all() -> [sample_test].

% Sample test case
sample_test(_Config) ->
    ?assertEqual(2, 1 + 1).
  • -module(example_SUITE).: Defines the test suite module.
  • all/0: Specifies test cases in the suite.
  • sample_test/1: A simple test case using Common Test assertions.

 

Running Tests with ct_run

To execute your test suite, use:

ct_run -dir test/

This will:

  • Discover and execute test cases in the test/ directory.
  • Generate logs and reports in the logs/ directory.

 

After running the tests, Common Test provides detailed logs and reports, making it easier to debug failures.

With your Common Test suite set up, the next step is to explore writing more complex test cases, handling test dependencies, and improving test coverage for your Erlang applications.

 

Structure of a Common Test Suite

A Common Test suite is structured to support modular, maintainable, and reusable test cases. It follows a standardized naming convention and lifecycle methods to handle setup and teardown operations efficiently.

 

Test Suite, Test Cases, and Hooks

  • Test Suite: A test suite is a module containing multiple test cases. Each test suite must be named with the _SUITE.erl suffix (e.g., my_tests_SUITE.erl).
  • Test Cases: Individual test functions that validate specific behaviors of the system.
  • Hooks: Special functions (init_per_suite, end_per_testcase, etc.) used to set up and clean up test environments.

 

Organizing test files

Common Test expects test suites to follow a specific file naming convention and directory structure:


my_project/
│── src/
│── test/
│   ├── my_tests_SUITE.erl  % Test suite file
│   ├── another_SUITE.erl   % Another test suite
│   └── test_helper.erl     % Helper module (optional)
│── rebar.config

 

Each test suite should be placed in the test/ directory and named following the pattern:

  • Correct: my_module_SUITE.erl
  • Incorrect: my_module.erl

 

Test case lifecycle methods

Common Test provides lifecycle functions to set up and tear down test environments at different levels:

 

Suite-level hooks (Run once for the entire suite)

init_per_suite(Config) ->
    % Setup before all test cases
    [{db_connection, connect_to_db()} | Config].

end_per_suite(_Config) ->
     % Cleanup after all test cases
     disconnect_from_db().
  • init_per_suite/1: Runs before any test case in the suite. Used for initializing shared resources.
  • end_per_suite/1: Runs after all test cases. Used for cleanup.

 

Test case-level hooks (Run before and after each test case)

init_per_testcase(sample_test, Config) ->
    % Setup before each test case
    [{temp_file, create_temp_file()} | Config].

end_per_testcase(sample_test, _Config) ->
    % Cleanup after each test case
    delete_temp_file().
  • init_per_testcase/2: Runs before each test case. Useful for setting up individual test environments.
  • end_per_testcase/2: Runs after each test case. Used to clean up temporary resources.

 

Example: A complete Common Test suite

-module(my_tests_SUITE).
-compile(export_all).

-include_lib("common_test/include/ct.hrl").

%% Define the test cases in the suite
all() -> [sample_test].

%% Suite-level setup
init_per_suite(Config) ->
    io:format("Setting up test suite~n"),
    Config.

end_per_suite(_Config) ->
    io:format("Cleaning up test suite~n"),
    ok.

%% Test case-level setup
init_per_testcase(sample_test, Config) ->
    io:format("Setting up sample test~n"),
    Config.

end_per_testcase(sample_test, _Config) ->
    io:format("Cleaning up sample test~n"),
    ok.

%% A sample test case
sample_test(_Config) ->
    ?assertEqual(42, 6 * 7).

 

Summary

  • Test suites are named using the _SUITE.erl suffix and stored in the test/ directory.
  • Each suite contains test cases and lifecycle hooks.
  • Lifecycle hooks (init_per_suite, end_per_testcase, etc.) help manage test setup and teardown.
  • Common Test follows a structured approach to testing, ensuring reliability and maintainability in Erlang applications.

By understanding this structure, you can build more robust and scalable test suites in Common Test!

 

Writing and running tests

Writing and executing tests in Common Test follows a structured approach, ensuring robustness and maintainability. In this section, we’ll explore how to define test cases, use assertions, leverage test fixtures for setup and teardown, and execute tests effectively.

 

Defining test cases and using assertions

A test case in Common Test is simply a function that takes a configuration parameter and executes assertions. The function must be exported and included in the `all/0` function, which lists all test cases in the suite.

Basic test case example

-module(my_tests_SUITE).
-compile(export_all).

-include_lib("common_test/include/ct.hrl").

%% Define test cases in the suite
all() -> [sample_test, failing_test].

%% A passing test case
sample_test(_Config) ->
    ?assertEqual(10, 5 + 5).

%% A failing test case
failing_test(_Config) ->
    ?assert(2 + 2 =:= 5).

 

Common assertions in Common Test
Common Test provides several built-in macros for assertions, including:

  • ?assert(Expression): Fails if Expression evaluates to false.
  • ?assertEqual(Expected, Actual): Fails if Expected does not equal Actual.
  • ?assertMatch(Pattern, Value): Fails if Value does not match Pattern.
  • ?assertException(Class, Term, Expression): Asserts that Expression raises a specific exception.

 

Example:

?assertMatch({ok, _}, my_function()).
?assertException(error, badarg, lists:nth(10, [1,2,3])).

 

Using test fixtures (Setup and teardown)

Test fixtures allow setting up the environment before running test cases and cleaning up after they complete.

 

Suite-level setup and teardown
Runs once before and after the entire suite:

init_per_suite(Config) ->
    io:format("Setting up test suite~n"),
    [{db_connection, connect_to_db()} | Config].

end_per_suite(_Config) ->
    io:format("Cleaning up test suite~n"),
    disconnect_from_db().

 

Test case-level setup and teardown
Runs before and after each test case:

init_per_testcase(sample_test, Config) ->
    io:format("Setting up sample test~n"),
    [{temp_file, create_temp_file()} | Config].

end_per_testcase(sample_test, _Config) ->
    io:format("Cleaning up sample test~n"),
    delete_temp_file().

 

Running tests and analyzing results

To execute Common Test suites, use the ct_run command.

 

Running tests from the command line

Navigate to the directory containing your test suites and run:

ct_run -dir test/

 

To specify a particular test suite:

ct_run -suite test/my_tests_SUITE

 

To run a single test case within a suite:

ct_run -suite test/my_tests_SUITE -case sample_test

 

Analyzing test results

After execution, Common Test generates logs and reports in the logs/ directory.

  • HTML reports: Located in logs/index.html, providing a structured view of test results.
  • Console output: Displays test execution details and failures.

 

Example console output:

========================
Testing my_tests_SUITE
========================
sample_test passed
failing_test failed: Expected 5, got 4
========================

 

By inspecting the logs/index.html, you can get more detailed failure explanations.

 

Summary

  • Define test cases using functions and assertions like ?assertEqual and ?assertMatch.
  • Use test fixtures (init_per_suite, init_per_testcase) to set up and clean up resources.
  • Run tests using ct_run -dir test/ and analyze results via logs and reports.

By following these steps, you can effectively write and execute Common Test cases in Erlang!

 

Key features of Common Test

Common Test provides a range of powerful features that make it well-suited for testing Erlang applications, especially those that require fault tolerance, concurrency, and distributed execution. Here’s a look at some of its key capabilities.

 

Logging and Reporting Capabilities

Common Test automatically generates detailed logs and reports to help developers analyze test results efficiently.

Logging

  • Each test execution produces logs stored in the logs/ directory.
  • Logs include execution details, errors, and debugging information.
  • You can add custom log messages using ct:log/2:
sample_test(_Config) ->
    ct:log("Running sample test with input ~p", [42]),
    ?assertEqual(42, some_function()).

 

Reporting

  • HTML reports: Located at logs/index.html, providing a structured summary of test results.
  • Plain text reports: Available in logs/run.log, useful for CI/CD pipelines.

 

Running ct_run with -label helps organize test runs:

ct_run -dir test/ -label regression_tests

 

Parameterized tests for multiple input cases

Common Test allows running the same test case with different inputs, reducing code duplication. This is useful for validating multiple scenarios with a single function.

 

Example: Running a Test with Multiple Inputs

all() -> [{group, parameterized_tests}].

groups() ->
    [{parameterized_tests, [], [test_with_params]}].

test_with_params(Config) ->
    Inputs = [{1, 2, 3}, {2, 3, 5}, {3, 4, 7}],
    lists:foreach(fun ({A, B, Expected}) ->
    ?assertEqual(Expected, A + B)
    end, Inputs).

Here, test_with_params will run multiple times, once for each set of parameters.

 

Parallel execution and distributed testing support

Common Test is designed to handle concurrent and distributed testing, making it ideal for systems that require high availability and scalability.

 

Running tests in parallel
By default, tests run sequentially, but you can enable parallel execution using groups:

groups() ->
    [{parallel_tests, [{parallel, true}], [test_case1, test_case2]}].

 

Distributed testing
Common Test can run test suites across multiple Erlang nodes, simulating real-world distributed environments. To enable distributed testing, start multiple nodes and specify them in ct_run:

ct_run -dir test/ -nodes '["node1@localhost", "node2@localhost"]'

This is useful for verifying message-passing, fault tolerance, and cluster behavior.

 

Integration with EUnit and PropEr

Common Test can be combined with other Erlang testing frameworks like EUnit and PropEr to enhance test coverage.

 

Using EUnit in Common Test
Common Test can execute EUnit tests within a Common Test suite.

test_with_eunit(_Config) ->
    ?assertEqual(10, lists:sum([5, 5])).

To integrate EUnit, ensure EUnit tests are run inside a Common Test case.

 

Property-Based Testing with PropEr
PropEr allows generating randomized test inputs to check for edge cases. You can integrate it with Common Test for automated property-based testing.

prop_sum(_Config) ->
    ?assertEqual(A + B, B + A) || proper:quickcheck(?FORALL({A, B}, {integer(), integer()}, A + B =:= B + A)).

 

By combining Common Test with EUnit and PropEr, you can create a comprehensive testing strategy.

 

Summary

  • Logging and reporting: Automatic logs and structured HTML reports for easy debugging.
  • Parameterized tests: Run a test with multiple inputs to cover different scenarios.
  • Parallel & distributed testing: Execute tests concurrently and across multiple nodes.
  • Integration with EUnit & PropEr: Leverage unit and property-based testing within Common Test.

These features make Common Test a powerful framework for ensuring the robustness of Erlang applications!

 

Best practices for using Common Test

To maximize the effectiveness of Common Test, it’s essential to follow best practices that enhance maintainability, reliability, and efficiency. This section covers key strategies for writing clear, robust, and scalable test suites in Erlang.

 

Structuring Test Suites for Maintainability

A well-organized test suite makes debugging and extending tests easier. Follow these guidelines:

Use clear naming conventions:

  • Test suites should follow the *_SUITE.erl naming pattern (e.g., auth_SUITE.erl).
  • Test cases should have descriptive names (e.g., valid_user_login/1 instead of test1/1).

 

Group related tests:

  • Use groups() to organize similar test cases together.
  • Define dependencies between groups when needed.
groups() ->
    [{authentication_tests, [], [valid_login, invalid_login]}].

 

Separate Unit, Integration, and System Tests:

  • Keep unit tests lightweight and fast.
  • Integration tests should involve external dependencies like databases.
  • System tests should verify distributed behavior.

 

Writing clear and deterministic test cases

Test cases should be clear, isolated, and repeatable to avoid flaky tests.

 

Minimize external dependencies:

  • Mock external services instead of relying on live endpoints.
  • Use test doubles or predefined datasets.

 

Ensure idempotency:

  • A test should produce the same result every time it runs.
  • Clean up test data after execution.

 

Use Assertions Effectively:

  • Use ?assert, ?assertEqual, and ?assertMatch for clarity.
valid_login(_Config) ->
    Response = auth:login("user", "password"),
    ?assertMatch({ok, _}, Response).

 

Efficiently testing concurrent and distributed systems

Since Erlang applications often rely on concurrency and distributed execution, Common Test provides features for testing these scenarios effectively.

 

Run tests in parallel:

  • Define parallel execution groups to test concurrent behavior.
groups() ->
    [{parallel_tests, [{parallel, true}], [case1, case2, case3]}].

 

Simulate network failures:

  • Use Chaos testing principles by shutting down nodes during execution.
ct_run -dir test/ -nodes '["node1@localhost", "node2@localhost"]'

 

Monitor process behavior:

  • Use erlang:monitor/2 to verify process lifecycles during testing.
Pid = spawn(fun() -> some_long_running_process() end),
MonitorRef = erlang:monitor(process, Pid),
receive
    {'DOWN', MonitorRef, process, Pid, Reason} ->
        ?assertMatch(normal, Reason)
end.

 

Debugging and troubleshooting test failures

Test failures are inevitable, but proper debugging techniques can help identify issues quickly.

 

Use Common Test’s logging mechanism:

  • Add ct:log/2 messages to capture intermediate values.
sample_test(_Config) ->
    ct:log("Checking login function with user ~p", ["test_user"]),
    ?assertEqual(ok, auth:login("test_user", "test_pass")).

 

Analyze logs and reports:

  • Look at logs/index.html for a summary.
  • Check logs/run.log for step-by-step execution details.

 

Rerun failing tests with verbose output:

ct_run -dir test/ -verbose

 

Enable debugging tools:

  • Attach an Erlang shell to a running test node for real-time inspection.
erl -sname debug -remsh node1@localhost

 

Summary of best practices

  • Organize tests properly: Use structured naming, groups, and clear separation of test types.
  • Write deterministic tests: Ensure they are repeatable, isolated, and do not rely on external state.
  • Test concurrency and distributed behavior: Use parallel execution, process monitoring, and fault simulation.
  • Debug efficiently: Utilize logging, reports, and debugging tools to investigate failures.

By following these best practices, you can ensure Common Test helps you build robust and fault-tolerant Erlang applications.

 

Conclusion

Testing is a crucial part of building fault-tolerant, scalable, and reliable applications in the Erlang ecosystem. Common Test, as a battle-tested framework from Erlang/OTP, provides robust tools for writing and executing unit, integration, and system tests in a structured and maintainable way.

 

Recap of Common Test’s benefits

  • Scalability: Supports testing concurrent and distributed systems efficiently.
  • Structured testing: Organizes test cases using suites, groups, and hooks.
  • Powerful logging & reporting: Generates detailed execution reports for debugging.
  • Parallel & distributed testing: Runs tests across multiple nodes.
  • Integration support: Works alongside EUnit, PropEr, and other testing tools.

 

Why You Should Use Common Test

If you’re working on an Erlang application — whether in telecom, fintech, or large-scale distributed systems— integrating Common Test will help ensure stability and reliability. It offers a comprehensive, flexible approach to testing, making it ideal for verifying complex system behaviors.

 

Additional resources

Check out the Ada Beat Functional Programming blog for more topics, including functional programming principles, summaries of MeetUps, language specific articles, and much more. Whether you’re interested in functional programming theory or practical application, we have something for everyone.