Integration testing

Unit tests are testing one module in isolation at a time: they're small and can test private code. Integration tests are external to your crate and use only its public interface in the same way any other code would. Their purpose is to test that many parts of your library work correctly together.

Scarb looks for integration tests in tests directory next to src.

File src/lib.cairo:

// Define this in a crate called `adder`.
pub fn add(a: u32, b: u32) -> u32 {
    a + b
}

File with test: tests/integration_test.cairo:

#[test]
fn test_add() {
    assert(adder::add(3, 2) == 5, 'addition failed');
}

Running tests with scarb test command:

$ scarb test 
     Running test adder (snforge test)
    Blocking waiting for file lock on registry db cache
    Blocking waiting for file lock on registry db cache
   Compiling test(listings/testing/integration_testing/Scarb.toml)
   Compiling test(listings/testing/integration_testing/Scarb.toml)
    Finished `dev` profile target(s) in 11 seconds


Collected 1 test(s) from adder package
Running 0 test(s) from src/
Running 1 test(s) from tests/
[PASS] adder_integrationtest::integration_test::test_add (gas: ~1)
Tests: 1 passed, 0 failed, 0 skipped, 0 ignored, 0 filtered out

If the tests directory does not contain a lib.cairo file, each Cairo source file in the tests directory is compiled as a separate crate. In order to share some code between integration tests we can define a lib.cairo file in the tests directory, which will create a single target named {package_name}_tests, and use its contents within tests by importing it.

File tests/common.cairo:

pub fn setup() { // some setup code, like creating required variables, etc.
}

File with test: tests/lib.cairo

// importing common module.
mod common;

#[test]
fn test_add() {
    // using common code.
    common::setup();
    assert(adder::add(3, 2) == 5, 'addition failed');
}

Creating the module as tests/lib.cairo is recommended to make the tests directory behave like a regular crate, avoiding each file being compiled as a separate test crate.