Chapter 4: Testing your Walnut contract
In this chapter, you’ll write tests to verify that the Walnut contract behaves as expected under various scenarios. Testing ensures the functionality, fairness, and access control mechanisms of your contract work seamlessly, particularly in multi-round gameplay. Estimated Time: ~15 minutes.
Getting Started
Navigate to the test folder in your Walnut App and open the Walnut.t.sol file located at:
packages/contracts/test/Walnut.t.solThis file is where you’ll write all the test cases for the Walnut contract. Start with the following base code:
// SPDX-License-Identifier: MIT License
pragma solidity ^0.8.13;
import {Test, console} from "forge-std/Test.sol";
import {Walnut} from "../src/Walnut.sol";
contract WalnutTest is Test {
Walnut public walnut;
function setUp() public {
// Initialize a Walnut with shell strength = 2 and kernel = 0
walnut = new Walnut(2, suint256(0));
}
}The setUp() function initializes the Walnut contract for use in all test cases.
Writing Test Cases
Start off with testing the basic functionalities, hit , shake , look and reset
Core functionalities
Basic hit functionality
Ensures the Walnut’s shell can be cracked by shellStrength number of hits.
Basic shake functionality
Validates that shaking the Walnut increments the kernel value.
Reset functionality
Now, test for the restrictive/conditional nature of these basic functionalities.
Restricting Actions
Preventing
hitwhen shell is cracked
Ensures that hitting a cracked shell is not allowed.
Preventing
shakewhen shell is cracked
Ensures that shaking the Walnut after the shell is cracked is not allowed.
Preventing
lookwhen shell is intact
Ensures that the kernel cannot be revealed unless the shell is fully cracked.
Preventing
resetwhen shell is intact
Validates that the Walnut cannot be reset unless the shell is fully cracked.
Now, test for more complex scenarios.
Complex scenarios
Sequence of Multiple Actions
Ensures that the Walnut behaves correctly under a sequence of hits and shakes.
Prevent Non-Contributors From Using
look()
Ensures that only contributors in the current round can call look() .
Contributor Tracking Across Rounds
Validates that contributions are tracked independently for each round. The test has one contributor hit both times and crack the shell in the first round, and a different contributor hit and crack the shell in the second round. We check for the fact the second round contributor cannot see the kernel after the first round and the first round contributor cannot see the kernel after the second.
You can find the entire test file here.
Test out the file by running the following inside the packages/contracts directory:
The contract has been tested, time to deploy it!
Last updated

