Ink! Developer Workshop - Web3bridge Edition

Objectives

Ink! Unit Testing Introduction

Unit tests are very vital when it comes to smart contract development. Ideally, writing a smart contract should be test-driven (write tests first, then build smart contract to pass the tests). In a large team, the requirements come first and these can be used to build test suites. Then when the contract is successfully tested and compiled, a E2E test can then be used to test all full functionalities

Ink! Unit testing works the same as normal Rust unit tests, to enable existing Rust engineers to work well with it. The major differences are, the unit tests must be declared within the contract module (inside the *#[ink::contract]* ) and each test function is marked with an *#[ink::test]* macro.

#[ink::contract]
mod contract {
	
	#[cfg(test)]
	mod tests { 
		use super::*;  // import all from super
	}
}

Once we got this setup, we can then define our test cases, an example unit test for the constructor (new) can be written as follows:

#[ink::test]
#[should_panic()]
fn contract_instantiation_works() {
	// Instantiate expects a total supply
	let total_supply = U256::from(1000);
	let instance = ContractInstance::new_with_supply(total_supply);
	
	assert_eq!(instance.total_supply, total_supply, "Total supply must match the instantiated");
}

A successful unit test run

A successful unit test run

Mocking on-chain scenario in Unit tests