How can I set a caller in ink! contract unit testing function?

Viewed 111
fn do_check(&mut self) -> Result<()> {
    let caller = self.env().caller();
    ...
}

I am writing a test function for do_check function. Here, I want to set a caller but not sure how to do that.

#[cfg(test)]
mod tests {
    use super::*;
    use ink_lang as ink;

    #[ink::test]
    fn do_check_works() {
        let mut test = Test::new();
        // here I want to set a caller for calling do_check
        test.do_check();
        ...
1 Answers

You can set the caller using set_caller from ink_env:

let account = AccountId::from([0x1; 32]);
ink_env::test::set_caller::<ink_env::DefaultEnvironment>(account);

EDIT: Currently, you need the experimental unit test engine. Add this above your test mod:

#[cfg(feature = "ink-experimental-engine")]

And add the dependency in your toml file:

ink-experimental-engine = ["ink_env/ink-experimental-engine"]

See the examples in the ink repo for more details.

Related