2
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();
        ...
E_net4
  • 27,810
  • 13
  • 101
  • 139
True
  • 696
  • 5
  • 20

1 Answers1

3

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);

See the examples in the ink-examples repo for more details.

forgetso
  • 2,194
  • 14
  • 33
  • 1
    ink_env::test::set_caller::(bob); | ^^^^^^^^^^ not found in `ink_env::test` – True Nov 04 '21 at 13:47
  • set_caller is not found in ink_env::test – True Nov 04 '21 at 13:47
  • You need to use 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"]` – forgetso Nov 04 '21 at 14:49
  • Experimental engine flag is no longer needed – forgetso Jun 09 '23 at 09:00