Testing ICP Canisters Properly: Unit Tests, PocketIC, Upgrades, Time, and Multi-Canister Failures
Thomas ·
The previous guides in this series covered persistent upgrades, inter-canister architecture, Internet Identity, and certified queries. All four have something in common: some of their most dangerous failure modes only appear once code is running as an actual canister. A pure Motoko function can be unit tested easily. An upgrade cannot. Neither can caller , timers, stable state restoration, realistic inter-canister messaging, or most lifecycle behavior. For those, I use PocketIC . PocketIC is now the testing engine underneath the icp CLI's local environment, and the current developer tooling describes it as a lightweight deterministic IC replica that requires no daemon, exposed ports, or Docker. The goal of this guide is not to show how to write an assert . It is to build a testing strategy that catches the kinds of bugs that actually destroy canister state or break production workflows. The testing stack I recommend I would divide ICP tests into three layers: E2E. Browser/UI and very few tests. PocketIC. Real Wasm and IC behavior, upgrades, callers, timers, multiple canisters. Unit. Pure Motoko logic, and many fast tests. The mistake is choosing only one. If everything is a PocketIC test, development becomes unnecessarily heavy. If everything is a unit test, you never actually test the environment your Wasm will execute inside. The boundary should be simple: If the behavior depends on ICP itself, test it in PocketIC. Use current tooling, not a legacy local replica workflow For Motoko, I would pin both the compiler and PocketIC through Mops: Plain text Bash / Shell C C++ C# CSS Candid Go HTML / XML Java JavaScript JSON Kotlin Markdown Motoko PHP Python Ruby Rust SQL Swift TypeScript YAML Diff mops toolchain use moc latest mops toolchain use pocket-ic 15.0.0 This writes the versions into mops.toml . Mops currently supports managing moc , Wasmtime, PocketIC, lintoko , and wasm-opt as project-local toolchain dependencies. The important part is not that PocketIC happens to be version 15.0.0 in that example. The important part is pinning it. Do not let developer A, developer B, and CI silently execute the same test suite against different replica versions. Then: Plain text Bash / Shell C C++ C# CSS Candid Go HTML / XML Java JavaScript JSON Kotlin Markdown Motoko PHP Python Ruby Rust SQL Swift TypeScript YAML Diff mops install can reproduce the selected toolchain. For local application deployment, continue using: Plain text Bash / Shell C C++ C# CSS Candid Go HTML / XML Java JavaScript JSON Kotlin Markdown Motoko PHP Python Ruby Rust SQL Swift TypeScript YAML Diff icp network start -d icp deploy The current icp local network itself uses PocketIC underneath. You do not need dfx start merely to get an IC-like environment anymore. Start with pure logic Suppose our application awards reputation. Do not bury the rule directly inside an actor: Plain text Bash / Shell C C++ C# CSS Candid Go HTML / XML Java JavaScript JSON Kotlin Markdown Motoko PHP Python Ruby Rust SQL Swift TypeScript YAML Diff public shared ({ caller }) func award(points : Nat ) : async () { // 80 lines of validation and calculations }; Extract the calculation: Plain text Bash / Shell C C++ C# CSS Candid Go HTML / XML Java JavaScript JSON Kotlin Markdown Motoko PHP Python Ruby Rust SQL Swift TypeScript YAML Diff module ReputationLogic { public func calculateAward( current : Nat , requested : Nat , dailyRemaining : Nat , ) : Nat { if (requested > dailyRemaining) { dailyRemaining; } else { requested; }; }; }; Now most edge cases do not require a replica. For example: Plain text Bash / Shell C C++ C# CSS Candid Go HTML / XML Java JavaScript JSON Kotlin Markdown Motoko PHP Python Ruby Rust SQL Swift TypeScript YAML Diff import ReputationLogic "../src/ReputationLogic" ; assert ( ReputationLogic.calculateAward( 100 , 25, 50 ) == 25 ); assert ( ReputationLogic.calculateAward( 100, 75, 50 ) == 50 ); Put Motoko tests under: Plain text Bash / Shell C C++ C# CSS Candid Go HTML / XML Java JavaScript JSON Kotlin Markdown Motoko PHP Python Ruby Rust SQL Swift TypeScript YAML Diff test/ with filenames such as: Plain text Bash / Shell C C++ C# CSS Candid Go HTML / XML Java JavaScript JSON Kotlin Markdown Motoko PHP Python Ruby Rust SQL Swift TypeScript YAML Diff reputation.test.mo and run: Plain text Bash / Shell C C++ C# CSS Candid Go HTML / XML Java JavaScript JSON Kotlin Markdown Motoko PHP Python Ruby Rust SQL Swift TypeScript YAML Diff mops test Mops runs Motoko test files in parallel and supports interpreter, Wasmtime, and replica-backed modes. For ordinary deterministic business logic, the default interpreter is exactly what I want. Fast tests should remain fast. Watch them while developing For tight development loops: Plain text Bash / Shell C C++ C# CSS Candid Go HTML / XML Java JavaScript JSON Kotlin Markdown Motoko PHP Python Ruby Rust SQL Swift TypeScript YAML Diff mops watch --test or, if you also want warnings and formatting: Plain text Bash / Shell C C++ C# CSS Candid Go HTML / XML Java JavaScript JSON Kotlin Markdown Motoko PHP Python Ruby Rust SQL Swift TypeScript YAML Diff mops watch -wtf Current Mops separates the watch tasks deliberately: specifying only --test does not implicitly enable formatting and warning checks. I would still have CI independently run: Plain text Bash / Shell C C++ C# CSS Candid Go HTML / XML Java JavaScript JSON Kotlin Markdown Motoko PHP Python Ruby Rust SQL Swift TypeScript YAML Diff mops check mops test A watch process is a developer convenience, not the build gate. What belongs in PocketIC? Now consider this method: Plain text Bash / Shell C C++ C# CSS Candid Go HTML / XML Java JavaScript JSON Kotlin Markdown Motoko PHP Python Ruby Rust SQL Swift TypeScript YAML Diff public shared ({ caller }) func createProfile( username : Text ) : async () { if ( Principal . isAnonymous (caller)) { Runtime . trap ( "Authentication required" ); }; profiles. add (caller, username); }; You can unit test the username validation. But the important integration question is: Does Alice's signed call actually arrive as Alice? That requires IC execution. Likewise: Does state survive this Wasm upgrade? Does a timer actually fire? Can canister A call canister B? Does an anonymous call get rejected? What happens when the callee traps? Those are PocketIC tests. PocketIC deploys compiled Wasm into an IC execution environment and makes real query/update calls against it. DFINITY specifically recommends it for upgrade hooks, stable-memory behavior, and multi-canister interactions. Do not test persistence by reinstalling the same source This connects directly to the first guide. Suppose version 1 contains: Plain text Bash / Shell C C++ C# CSS Candid Go HTML / XML Java JavaScript JSON Kotlin Markdown Motoko PHP Python Ruby Rust SQL Swift TypeScript YAML Diff type User = { name : Text ; }; and version 2 becomes: Plain text Bash / Shell C C++ C# CSS Candid Go HTML / XML Java JavaScript JSON Kotlin Markdown Motoko PHP Python Ruby Rust SQL Swift TypeScript YAML Diff type User = { name : Text ; joinedAt : Int ; }; A weak "upgrade test" builds and installs the current code, writes data, upgrades using current code again, and checks data. That proves almost nothing about your migration. The production risk is: Plain text Bash / Shell C C++ C# CSS Candid Go HTML / XML Java JavaScript JSON Kotlin Markdown Motoko PHP Python Ruby Rust SQL Swift TypeScript YAML Diff OLD WASM │ │ real old state ▼ NEW WASM So your test needs two artifacts: Plain text Bash / Shell C C++ C# CSS Candid Go HTML / XML Java JavaScript JSON Kotlin Markdown Motoko PHP Python Ruby Rust SQL Swift TypeScript YAML Diff fixtures/ ├── backend-v1.wasm └── backend-v2.wasm or an equivalent reproducible build process. Then: Install v1 Create realistic v1 state Upgrade to v2, Verify the transformed state. That is a migration test. Keep released Wasm fixtures For important canisters, I would seriously consider preserving production release Wasm files as test fixtures. Why? Six months later, your source tree may no longer build version 1 cleanly. Dependencies disappear. Compiler versions move. Build scripts change. Yet you may still need to prove that the deployed v1 became candidate v7. A deployed Wasm artifact is the thing your production state was actually executing against. That makes it a valuable regression fixture. The IC itself exposes the SHA-256 hash of deployed canister Wasm, which is also useful when matching a test artifact to a real deployed version. Test realistic state, not three toy records Suppose a migration loops through every user. Testing Alice, Bob, and Carol proves correctness for three users. It says very little about 400,000 users especially if the migration performs O(n²) work. I would generate state near realistic production boundaries. For example: Plain text Bash / Shell C C++ C# CSS Candid Go HTML / XML Java JavaScript JSON Kotlin Markdown Motoko PHP Python Ruby Rust SQL Swift TypeScript YAML Diff let USER_COUNT = 50_000 ; Populate it, then upgrade. Measure whether the migration completes. A migration that is logically correct but exceeds execution limits is still a broken migration. This is one reason Mops also provides PocketIC-backed benchmarking through: Plain text Bash / Shell C C++ C# CSS Candid Go HTML / XML Java JavaScript JSON Kotlin Markdown Motoko PHP Python Ruby Rust SQL Swift TypeScript YAML Diff mops bench Benchmarks require a pinned PocketIC version, and Mops can emit benchmark results as Markdown for tracking over time. Test state invariants, not just individual records After an upgrade, checking if Alice still exists is useful. Checking that all 50,000 users still exist is better. Checking invariants is better again: Plain text Bash / Shell C C++ C# CSS Candid Go HTML / XML Java JavaScript JSON Kotlin Markdown Motoko PHP Python Ruby Rust SQL Swift TypeScript YAML Diff user count unchanged all usernames remain unique all balances sum to the same total nextId > every existing ID every post owner exists every index points to a valid record For a token-like system, I would calculate the sum of balances before the upgrade and after the upgrade and require equality unless the migration explicitly changes supply. This catches corruption that individual fixture assertions often miss. Test the exact bug you are afraid of The second guide discussed idempotency. Suppose we designed: Plain text Bash / Shell C C++ C# CSS Candid Go HTML / XML Java JavaScript JSON Kotlin Markdown Motoko PHP Python Ruby Rust SQL Swift TypeScript YAML Diff applyAward ( operationId : Nat , user : Principal , points : Nat , ) so retries cannot award points twice. Do not merely unit test the internal map. Test the real public API: Plain text Bash / Shell C C++ C# CSS Candid Go HTML / XML Java JavaScript JSON Kotlin Markdown Motoko PHP Python Ruby Rust SQL Swift TypeScript YAML Diff applyAward ( 1042 , Alice , 10 ) applyAward ( 1042 , Alice , 10 ) applyAward ( 1042 , Alice , 10 ) Then require: Plain text Bash / Shell C C++ C# CSS Candid Go HTML / XML Java JavaScript JSON Kotlin Markdown Motoko PHP Python Ruby Rust SQL Swift TypeScript YAML Diff Alice = 10 not: Plain text Bash / Shell C C++ C# CSS Candid Go HTML / XML Java JavaScript JSON Kotlin Markdown Motoko PHP Python Ruby Rust SQL Swift TypeScript YAML Diff Alice = 30 The test should resemble the production failure mode. If you are worried about duplicate messages, send duplicate messages. If you are worried about upgrade corruption, perform an upgrade. If you are worried about authorization, use two identities. Authorization tests need multiple principals The Internet Identity guide emphasized that the backend should trust: Plain text Bash / Shell C C++ C# CSS Candid Go HTML / XML Java JavaScript JSON Kotlin Markdown Motoko PHP Python Ruby Rust SQL Swift TypeScript YAML Diff caller rather than a principal supplied by the frontend. Your tests should prove that boundary. Create at l