如何在 substrate 3.0.0 中测试事件?
How to test events in substrate 3.0.0?
在 substrate 2.0.1 中,其代码如下:
mod simple_event {
pub use crate::Event;
}
impl_outer_event! {
pub enum TestEvent for TestRuntime {
simple_event,
frame_system<T>,
}
}
https://github.com/substrate-developer-hub/recipes/blob/master/pallets/simple-event/src/tests.rs
但是添加 impl_outer_event 会导致 substrate 3.0.0 出错:
/ frame_support::construct_runtime!(
14 | | pub enum Test where
15 | | Block = Block,
16 | | NodeBlock = Block,
... |
21 | | }
22 | | );
| |__^ duplicate definitions for `outer_event_metadata`
...
58 | / impl_outer_event! {
59 | | pub enum TestEvent for Test {
60 | | simple_event<T>,
61 | | frame_system<T>,
62 | | }
63 | | }
| |_- other definition for `outer_event_metadata`
如何解决?
在 Substrate 3.0 中,您在完整运行时中使用的测试中使用相同的 construct_runtime!
宏。您可以在 Substrate 存储库中查看如何以新方式测试事件的示例。
我就是这样做的。
在mock.rs文件中,我改为:
pub fn new_test_ext() -> sp_io::TestExternalities {
let t = frame_system::GenesisConfig::default().build_storage::<Test>().unwrap();
let mut ext = sp_io::TestExternalities::new(t);
ext.execute_with(|| System::set_block_number(1));
ext
}
接收事件。
在tests.rs中:
use crate::{RawEvent};
#[test]
fn my_test() {
new_test_ext().execute_with(|| {
assert_ok!(TemplateModule::check_peers_deparment(Origin::signed(2), 1));
let expected_event = Event::pallet_template(RawEvent::PeerDepartment(1, 2));
assert_eq!(System::events()[0].event, expected_event);
});
}
在 substrate 2.0.1 中,其代码如下:
mod simple_event {
pub use crate::Event;
}
impl_outer_event! {
pub enum TestEvent for TestRuntime {
simple_event,
frame_system<T>,
}
}
https://github.com/substrate-developer-hub/recipes/blob/master/pallets/simple-event/src/tests.rs
但是添加 impl_outer_event 会导致 substrate 3.0.0 出错:
/ frame_support::construct_runtime!(
14 | | pub enum Test where
15 | | Block = Block,
16 | | NodeBlock = Block,
... |
21 | | }
22 | | );
| |__^ duplicate definitions for `outer_event_metadata`
...
58 | / impl_outer_event! {
59 | | pub enum TestEvent for Test {
60 | | simple_event<T>,
61 | | frame_system<T>,
62 | | }
63 | | }
| |_- other definition for `outer_event_metadata`
如何解决?
在 Substrate 3.0 中,您在完整运行时中使用的测试中使用相同的 construct_runtime!
宏。您可以在 Substrate 存储库中查看如何以新方式测试事件的示例。
我就是这样做的。
在mock.rs文件中,我改为:
pub fn new_test_ext() -> sp_io::TestExternalities {
let t = frame_system::GenesisConfig::default().build_storage::<Test>().unwrap();
let mut ext = sp_io::TestExternalities::new(t);
ext.execute_with(|| System::set_block_number(1));
ext
}
接收事件。
在tests.rs中:
use crate::{RawEvent};
#[test]
fn my_test() {
new_test_ext().execute_with(|| {
assert_ok!(TemplateModule::check_peers_deparment(Origin::signed(2), 1));
let expected_event = Event::pallet_template(RawEvent::PeerDepartment(1, 2));
assert_eq!(System::events()[0].event, expected_event);
});
}