Skip to main content
Smart contracts need both unit and sandbox tests:
  1. Unit tests exercise methods individually. They are written in Rust alongside the contract and run locally.
  2. Sandbox tests deploy the compiled contract to a local NEAR Sandbox and exercise it through transactions.
Use unit tests for contract logic and state changes. Use sandbox tests for behavior that depends on the runtime, including cross-contract calls, gas, attached deposits, and multiple accounts. Use both types of tests during local development. Sandbox tests handle local accounts, balances, and contract setup in code, so you do not need a public account, faucet tokens, or a wallet login. When you are ready to share your contract, deploy it to testnet before releasing on mainnet.
Unit tests allow you to test the contract methods individually. They are suitable to check the storage is updated correctly, and that methods return their expected values. They are written in Rust alongside the contract’s code and execute locally. To run the unit tests, simply navigate to the contract’s folder and run cargo test:
cargo test runs both unit and sandbox tests present in the project.

Snippet I: Testing a Counter

The tests in the Counter Example rely on basic functions to check that the increment, decrement, and reset methods work properly.
lib.rs
Cargo.toml

Snippet II: Modifying the Context

While doing unit testing you can modify the Environment variables through the VMContextBuilder. This will enable you to, for example, simulate calls from different users, with specific attached deposit and GAS. Here we present a snippet on how we test the donate method from our Donation Example by manipulating the predecessor and attached_deposit.
lib.rs
Cargo.toml

⚠️ Limitations

Unit tests are useful to check for code integrity, and detect basic errors on isolated methods. However, since unit tests do not run on a blockchain, there are many things which they cannot detect. Unit tests are not suitable for: For all these cases it is necessary to complement unit tests with sandbox tests.