• YouTube Channel
  • System Status
  • VS Code Extension
  • Incomplete Constructor Tests in Test Functions

    Overview

    What are Incomplete Constructor Tests?

    Incomplete constructor tests occur when test functions for smart contracts do not thoroughly verify all aspects of the contract's constructor. This can lead to missed initialization issues and potential vulnerabilities in the contract's initial state.

    Why are Incomplete Constructor Tests Problematic?

    Incomplete constructor tests can lead to several issues:

    Technical Example of Incomplete Constructor Tests

    
    pragma solidity ^0.8.0;
    import "./test.sol";
    
    contract TokenTest is Test {
        Token token;
    
        function testConstructor() public {
            token = new Token("MyToken", "MTK", 1000000);
            assertEq(token.name(), "MyToken");
            assertEq(token.symbol(), "MTK");
            // Missing checks for total supply and owner initialization
        }
    }
    
    

    In this example, the test function only checks the name and symbol of the token, but fails to verify the total supply and any other important initial states set by the constructor.

    Technical Example with Comprehensive Constructor Tests

    
    pragma solidity ^0.8.0;
    import "./test.sol";
    
    contract TokenTest is Test {
        Token token;
    
        function testConstructor(string memory name, string memory symbol, uint256 initialSupply) public {
            vm.assume(bytes(name).length > 0 && bytes(symbol).length > 0);
            vm.assume(initialSupply > 0 && initialSupply <= type(uint256).max);
    
            token = new Token(name, symbol, initialSupply);
            
            assertEq(token.name(), name);
            assertEq(token.symbol(), symbol);
            assertEq(token.totalSupply(), initialSupply);
            assertEq(token.balanceOf(address(this)), initialSupply);
            assertEq(token.owner(), address(this));
            
            // Test constructor reverts with invalid inputs
            vm.expectRevert("Name cannot be empty");
            new Token("", symbol, initialSupply);
            
            vm.expectRevert("Symbol cannot be empty");
            new Token(name, "", initialSupply);
            
            vm.expectRevert("Initial supply must be positive");
            new Token(name, symbol, 0);
        }
    }
    
    

    In this improved version, the test function comprehensively checks all aspects of the constructor, including:

    This ensures a thorough validation of the contract's initial state and constructor logic.