Amiya Behera
Amiya Behera

Reputation: 2270

How to test events in substrate 3.0.0?

In substrate 2.0.1, its has following code:

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

But adding impl_outer_event is giving error in 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`

https://github.com/substrate-developer-hub/substrate-node-template/blob/master/pallets/template/src/mock.rs

How to solve it?

Upvotes: 1

Views: 653

Answers (3)

Just to clarify one thing in the Amiya's example code.

This line:

System::set_block_number(1)

Is very important, because without it there will be no events generated! See this answer for more details

Upvotes: 1

Amiya Behera
Amiya Behera

Reputation: 2270

This is how I have done.

In mock.rs file, I changed to:

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
}

to receive events.

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

}

Upvotes: 4

JoshOrndorff
JoshOrndorff

Reputation: 1701

In Substrate 3.0 you use the same construct_runtime! macro in tests that you use in the full runtime. You can see an example of how to test events the new way in the Substrate repository itself.

https://github.com/paritytech/substrate/blob/83942f58fc859ef5790351691e1ef665d79f0ead/frame/balances/src/tests.rs#L470-L473

Upvotes: 4

Related Questions