Search code examples
unit-testingrustsubstraterust-ink

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


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

Solution

  • 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.