Unit Tests
Ralph offers an experimental testing framework for writing unit tests directly within smart contracts. This feature requires Alephium full node version 3.15.2 or higher and the web3 SDK version 2.0.0-rc.2 or above.
info
The Ralph testing framework is currently experimental and evolving. It's particularly well-suited for testing pure functions. Testing with TypesScript SDK is recommended for complex contract interactions.
Basic Test Syntax
Tests are written in test blocks with descriptive text explaining what is being tested:
Contract Calculator() {
pub fn add(a: U256, b: U256) -> U256 {
return a + b
}
test "should add two numbers correctly" {
testEqual!(add(2, 3), 5)
testEqual!(add(0, 10), 10)
testEqual!(add(100, 200), 300)
}
}
Assertion Functions
testEqual! - Equality Testing
Compares two values for exact equality:
test "should return correct fibonacci numbers" {
testEqual!(fibonacci(0), 0)
testEqual!(fibonacci(5), 5)
testEqual!(fibonacci(10), 55)
}
testCheck! - Boolean Assertions
Verifies boolean conditions:
test "should validate age correctly" {
testCheck!(isValidAge(25))
testCheck!(!isValidAge(17))
}
testError! - Specific Error Testing
Tests that a function throws a specific error code:
test "should throw insufficient funds error" {
testError!(withdraw(balance + 1), ErrorCodes.InsufficientFunds)
testError!(withdraw(0), ErrorCodes.InvalidAmount)
}