Canister unit tests

Hi fam,

I’m writing a canister in Rust. I wonder what’s the best way to do unit tests (not integration tests) using cargo test?

Currently anything involving ic_cdk::api::{caller, id, time} panics:
panicked at 'msg_caller_size should only be called inside canisters.'

I understand they can be tested in integration tests, but is there a way to unit test them?

IMO the best way is to split canister interface and canister logic so you can test the logic without a canister interface. Have a look at how we do it for the asset canister: interface and canister logic

Another option is to use use the StateMachine to run your canister on a replica with a Rust interface. I don’t know of a public example of StateMachine tests off the top of my head :frowning_face:

I’m writing an on-chain governance framework that heavily relies on caller and time, I don’t think it’s possible to separate the logic for testing.

I will take a look at StateMachine though, it looks interesting.

you can use the Bitfinity sdk for this.

Or ic-state machine tests.