Basics
Learn how to setup the scaffolding required to write tests for your pallet.
This guide steps through how to use mock.rs
and test.rs
as a basis for testing your pallet. We'll be using the node template for the scaffolding of the mock.rs
file and an arbitrary pallet — called pallet-testing
— to give this guide some context. This pallet will contain a single function called add_value
, that takes an origin and a u32
and returns Ok(())
if the value is less than or equal to a constant called MaxValue
that we specify in the mock runtime.
Use the template node as boilerplate
Inside pallet-testing/src
, the first thing we need to do is create two empty files: mock.rs
and tests.rs
.
Paste in the contents from template/src/mock.rs
. We'll use this as boilerplate which we'll customize for our pallet-testing
pallet.
Create a mock runtime to test your pallet
Start by modifying
pallet-testing/src/mock.rs
to include thepallet-testing
pallet. This involves changes in the following code sections:Replace the first line with the name of the pallet, in our case
pallet_testing
:
Configure the mock runtime
In
frame_support::construct_runtime!
, replacepallet_template
with the name of your pallet, in our casepallet_testing
:Implement your pallet for the mock runtime. Replace
impl pallet_template::Config for Test {...}
with your configuration types and any constant values your pallet requires:
To put the mock runtime to use, we need to set up our tests.rs
file for the pallet-testing
pallet.
Setup and create tests
In tests.rs
, start by importing the dependencies you'll need from lib.rs
using super
:
Test that errors work as intended:
Create a test that should work:
And another that should fail:
Run your tests
Execute the following command from your pallet's directory:
Examples
tests in
pallet_template
tests in the
reward-coin
example pallet
Related material
Last updated