Foundry – How to Test if a Function Call Fails

foundry

I want to test if a function call fails using Foundry, how can I do that?

The function in question is one that spends all gas, I call it with:

level20.withdraw{gas : 10000 wei}(); and specify gas otherwise the test pend forever. With gas, the test fails and tell me that it's out of (good news, what I expected)

How can I write the test so that it doesn't fail and I'm testing that it fails?

Best Answer

I haven't used it specifically to test out of gas errors, but there are the expectRevert functions in forge-std/Vm.sol. Calling one of these functions will cause the vm to "catch" the revert in the following function call, and fail the test if the expected revert doesn't happen. The different variants of the function also allow you to assert that the error message is a certain value. Doing the following should work for you:

vm.expectRevert();
level20.withdraw{gas : 10000 wei}();
Related Topic