// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
contract SimpleStorage {
uint256 private storedData;
function set(uint256 x) public {
storedData = x;
}
function get() public view returns (uint256) {
return storedData;
}
}
测试脚本 SimpleStorage.test.sol:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import "forge-std/Test.sol";
import "../src/SimpleStorage.sol"; // 引入被测试的合约
contract SimpleStorageTest is Test {
SimpleStorage public simpleStorage;
address public owner = address(this); // 测试合约本身作为调用者
function setUp() public {
// 每个测试运行前初始化
simpleStorage = new SimpleStorage();
}
function testSetAndGet() public {
uint256 initialValue = simpleStorage.get();
assertEq(initialValue, 0, "Initial value should be 0");
uint256 newValue = 42;
simpleStorage.set(newValue);
uint256 retrievedValue = simpleStorage.get();
assertEq(retrievedValue, newValue, "Stored value should be set correctly");
}
function testSetWithDifferentValues() public {
simpleStorage.set(100);
assertEq(simpleStorage.get(), 100, "Should store 100");
simpleStorage.set(0);
assertEq(simpleStorage.get(), 0, "Should store 0");
simpleStorage.set(type(uint256).max);
assertEq(simpleStorage.get(), type(uint256).max, "Should store max uint256");
}
}