Skip to main content

Unit Tests

Unit tests are small tests that test one piece of functionality within a contract.

The following is an example of a unit test, written to test the increment contract. The contract has an increment function, that increases a counter value by one on every invocation. The following test invokes that contract's function several times, and checks that the value increases by one.

#![cfg(test)]
use crate::{IncrementContract, IncrementContractClient};
use soroban_sdk::Env;

#[test]
fn test() {
let env = Env::default();
let contract_id = env.register(IncrementContract, ());
let client = IncrementContractClient::new(&env, &contract_id);

assert_eq!(client.increment(), 1);
assert_eq!(client.increment(), 2);
assert_eq!(client.increment(), 3);
}

Ref: https://github.com/stellar/soroban-examples/blob/main/increment/src/test.rs

tip

Tests are written in Rust, alongside the contract. Same tools. Same APIs. Same SDK. No context switching! Use your favorite Rust tools and libraries that you'd use for any Rust test.

info

The Env created at the beginning of the test is not a simulation of the Soroban Environment. It's the same Soroban Environment that mainnet uses to execute contracts. There are only some minor differences: test utilities are enabled, and the storage backend is different.

It's a simple test, but it's a complete test. There's a full environment setup, used, and torn down in the test, and it happens fast. The Rust test harness runs all the tests for a contract in parallel and each will have its own isolated contract environment.

Most tests, even integration tests and fuzz tests, will look very similar to this unit test. They'll do four things:

  1. Create an environment, the Env.
  2. Register the contract(s) to be tested.
  3. Invoke functions using a client.
  4. Assert the outcome.