Setting up tests for your pallet
Get into the habit of writing tests as you write your pallet โ it's good practice!
#
GoalLearn how to setup the scaffolding required to write tests for your pallet.
#
Use casesWriting and running unit tests for a pallet.
#
OverviewThis 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.
#
Steps#
1. Use the template node as boilerplateInside 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 boilerpate
which we'll customize for our pallet-testing
pallet.
#
2. Create a mock runtime to test your palletStart by modifying pallet-testing/src/mock.rs
to include the pallet-testing
pallet. This involves changes in the following code sections:
#
DependenciesReplace the first line with the name of the pallet, in our case pallet_testing
:
#
Configure mock runtimeIn frame_support::construct_runtime!
, replace pallet_template
with the name of your pallet, in our
case pallet_testing
:
#
Implement your pallet for the mock runtimeReplace impl pallet_template::Config for Test {...}
with the 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.
#
3. Setup and create testsIn tests.rs
, start by importing the dependencies you'll need from lib.rs
using super
:
#
Testing that errors workThis will test whether the error works as intended:
#
Testing known working caseCreate a test that should work:
#
Testing known failing caseAnd another that should fail:
#
4. Run your testsExecute the following command from your pallet's directory: