3分钟Solidity: 14.3 Foundry错误测试

31 阅读1分钟

欢迎订阅专栏3分钟Solidity--智能合约--Web3区块链技术必学

Foundry错误

有关此内容的最新版本,请参阅 Cyfrin.io 上的Foundry错误(代码示例)

// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;

import "forge-std/Test.sol";

contract Error {
    error NotAuthorized();

    function throwError() external {
        require(false, "not authorized");
    }

    function throwCustomError() external {
        revert NotAuthorized();
    }
}

contract ErrorTest is Test {
    Error public err;

    function setUp() public {
        err = new Error();
    }

    // 以testFail开头的测试名称
    function testFail() public {
        err.throwError();
    }

    function testRevert() public {
        vm.expectRevert();
        err.throwError();
    }

    function testRequireMessage() public {
        vm.expectRevert(bytes("not authorized"));
        err.throwError();
    }

    function testCustomError() public {
        vm.expectRevert(Error.NotAuthorized.selector);
        err.throwCustomError();
    }

    // 给断言添加标签
    function testErrorLabel() public {
        assertEq(uint256(1), uint256(1), "test 1");
        assertEq(uint256(1), uint256(1), "test 2");
        assertEq(uint256(1), uint256(1), "test 3");
    }
}

Try on Remix