Solidity test internal function
To test an internal solidity function, create a child contract that inherits from the contract being tested, wrap the parent contract’s internal function with an external one, then test the external function in the child.
Foundry calls this inheriting contract a “harness” though others call it a “fixture.”
Don’t change the solidity function to become virtual
or public
to make it easier to extend, you want to test the contract you will actually deploy.
Here is an example.
contract InternalFunction {
function calculateReward(uint256 depositTime) internal view returns (uint256 reward) {
reward = (block.timestamp - depositTime) * REWARD_RATE_PER_SECOND;
}
}
The function above gives a linear reward rate for each unit of time that passes by.
The fixture (or harness) would look like this:
contract InternalFunctionHarness is InternalFunction {
function calculateReward(uint256 depositTime) external view returns (uint256 reward) {
reward = super.calculateReward(depositTime);
}
}
When you call a parent function that has the same name as the child, you must use the super
keyword of the function will call itself and go into infinite recursion.
Alternatively, you can explicitly label your test function as a harness or fixture as follows
contract InternalFunctionHarness is InternalFunction {
function…