Skip to main content

Setting up tests for your pallet

Get into the habit of writing tests as you write your pallet โ€” it's good practice!


Learn how to setup the scaffolding required to write tests for your pallet.

Use cases#

Writing and running unit tests for a pallet.


This guide steps through how to use and as a basis for testing your pallet. We'll be using the node template for the scaffolding of the 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.


1. Use the template node as boilerplate#

Inside pallet-testing/src, the first thing we need to do is create two empty files: and

Paste in the contents from template/src/ We'll use this as boilerpate which we'll customize for our pallet-testing pallet.

2. Create a mock runtime to test your pallet#

Start by modifying pallet-testing/src/ to include the pallet-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:

use crate as pallet_testing;

Configure mock runtime#

In frame_support::construct_runtime!, replace pallet_template with the name of your pallet, in our case pallet_testing:

TestingPallet: pallet_testing::{Module, Call, Storage, Event<T>},

Implement your pallet for the mock runtime#

Replace impl pallet_template::Config for Test {...} with the your configuration types and any constant values your pallet requires:

parameter_types! {
pub const MaxValue: u32 = 50;
impl pallet_testing::Config for Test {
type Event = Event;
type MaxValue = MaxValue;

To put the mock runtime to use, we need to set up our file for the pallet-testing pallet.

3. Setup and create tests#

In, start by importing the dependencies you'll need from using super:

use super::*;

Testing that errors work#

This will test whether the error works as intended:

fn error_works(){
new_test_ext().execute_with(|| {
TestingPallet::add_value(Origin::signed(1), 51),
"value must be <= maximum add amount constant"

Testing known working case#

Create a test that should work:

fn test_should_work() {
new_test_ext().execute_with(|| {
TestingPallet::add_value(Origin::signed(1), 10)

Testing known failing case#

And another that should fail:

fn test_should_fail() {
new_test_ext().execute_with(|| {
TestingPallet::add_value(Origin::signed(1), 100)

4. Run your tests#

Execute the following command from your pallet's directory:

cargo test


Related material#



Rust docs#

Was this guide useful?