如何在 ink 中设置来电!合同单元测试功能?

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

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

我正在为 do_check 函数编写测试函数。在这里,我想设置一个来电者,但不知道该怎么做。

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

您可以使用 set_callerink_env:

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

编辑:当前,您需要实验单元测试引擎。将此添加到您的测试上方 mod:

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

并在你的 toml 文件中添加依赖:

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

有关详细信息,请参阅墨水库中的 examples