Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Testing throws in Solidity
pragma solidity ^0.4.4;
/*
This is for testing if a transaction would throw.
Contract calls rethrow when it encounters errors.
Raw calls do not.
You wrap your contract you want to test in a ThrowProxy.
You prime it by calling the fallback function.
Then executing it.
False will be returned if it threw.
True will be return it it did not throw or OOG.
*/
contract ThrowProxy {
address public target;
bytes data;
function ThrowProxy(address _target) {
target = _target;
}
//prime the data using the fallback function.
function() {
data = msg.data;
}
function execute() returns (bool) {
return target.call(data);
}
}
contract Something {
function doThrow() {
throw;
}
function doNoThrow() {
//
}
}
contract TestSomething {
function testThrow() returns (bool) {
Something s = new Something();
ThrowProxy t = new ThrowProxy(address(s));
//prime the proxy.
Something(address(t)).doThrow();
//execute the call that is supposed to throw.
bool r = t.execute(); //r will be false if it threw. r will be true if it didn't.
//do assert here.
return r;
}
}
@simondlr

This comment has been minimized.

Copy link
Owner Author

@simondlr simondlr commented Dec 7, 2016

address(t).call(bytes4(bytes32(sha3("doThrow()"))));

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment