35

There are snippets and functions of Solidity code provided on this Ethereum Stack Exchange and other sites. What are ways to quickly test them, possibly debug a little, and play around?

39

One way is to use Remix, the browser-based Solidity realtime compiler and runtime Solidity (formerly named browser-solidity).

  1. Paste the code in Remix.
  2. Wrap the function inside a contract if needed. (Example: contract C { ... }.)
  3. Click Contract tab and then Create to instantiate the contract.
  4. Enter the desired input next to the function.
    • For bytes1 ... bytes32, use a quoted hex string, example "0xabcdef" for bytes3.
    • For bytes, use an array of hex strings, example: ["0xab", "0xcd", "0xef"].
    • For strings, make sure they are quoted.
    • For large numbers, make sure they are quoted too.
    • For an array, use [], example: ["hello", 42, "0xabcd"]
  5. Click the function to get the Result. The Result is ABI encoded.

Here is an example screenshot:

enter image description here

  • Is there a way to "console.log" stuff? – manidos Jul 27 '16 at 14:06
  • 2
    The closest equivalent is to use an event like event print(uint x), then in your function you can print(255), and you will see it show up in Solidity Browser. – eth Jul 28 '16 at 0:44
  • If you want to do this in the Remix IDE built into the Mist client, by default the "Create" button will prompt you to publish the transaction. To just run it like in this answer, switch the "Environment" dropdown to "Javascript VM". – Macil Aug 26 '17 at 7:59
16

I personally use Dapple for writing Solidity unit tests. It has the advantage of not requiring a Javascript testing framework layer, so you can stay entirely in Solidity. Plus I can use it to test contracts that use imports, which I'm not sure is possible in chriseth's browser-based Solidity.

Edit: The accepted answer is definitely a better option for someone just looking to get a taste of the language. I do still hold that Dapple's a better option for people like myself who like to stay on the command line and who might want to knock out a quick test to shine some light into some of the language's darker corners. (You may easily underestimate my preference for the command line. It's a little ridiculous and extends to knocking out short scripts so I can check websites without having to switch to a browser.)

That said, since answering this question I've found a tool called Solidity REPL which does exactly what the name implies: gives you a Solidity REPL on the command line. For futzing about with the language and doing quick sanity checks, as one might with something like Python, I recommend that tool over Dapple.

  • IMHO This allows for real unit testing as opposed to integration testing with your rpc client. – Juan Blanco Apr 10 '16 at 16:47
  • 1
    If you are doing mostly solidity-solidity code, this is a good approach. If you are writing an app with a lot of interaction with off-chain components I'd advise the other answer using truffle/pudding (or create your own) – Paul S Apr 10 '16 at 19:10
  • OP is not asking about unit testing, why don't you use Truffle or Embark? – niksmac Apr 11 '16 at 1:52
  • 1
    Truffle and Embark make a lot of sense for building browser-based dapps, and they're great for integration tests. But it's also nice to be able to isolate the thing you're testing and write unit tests. Most of my work is purely in Solidity, with other team members handling integration and user-facing components. Given my use case, Dapple is ideal. Probably also doesn't hurt that I helped make it! – ryepdx Apr 11 '16 at 3:28
13

There are a few ways to do testing of Solidity contracts. The easiest, at least in my opinion, is blackbox testing with Truffle. Contracts tend to be relatively small and self-contained, so blackbox testing seems appropriate here.

Truffle lets you write unit tests in Javascript using Pudding, an extension of web3, Mocha and Chai. A typical test looks like this:

contract('MetaCoin', function(accounts) {
  it("should put 10000 MetaCoin in the first account", function(done) {
    // Get a reference to the deployed MetaCoin contract, as a JS object.
    var meta = MetaCoin.deployed();

    // Get the MetaCoin balance of the first account, and assert that it's 10000.
    meta.getBalance.call(accounts[0]).then(function(balance) {
      assert.equal(balance.valueOf(), 10000, "10000 wasn't in the first account");
    }).then(done).catch(done);
  });
});
  • I forked and created my own environment, but I agree. Write automated regression tests for Solidity contracts. Saved me huge amounts of headaches on ~1000 lines of Solidity (so far) – Paul S Apr 10 '16 at 19:08
10

Another option is using EthereumJ implementation. We have recently released version 1.2.0 and it has nice feature specially for such cases. You may check the sample here

StandaloneBlockchain bc = new StandaloneBlockchain();

SolidityContract contract = bc.submitNewContract(
       "contract A { uint a; ... }"
);

contract.callFunction("funcName", "arg1", 2, new byte[] {1,2,3}, "arg4");
bc.createBlock()

System.out.println("Result: " + contract.callConstFunction("getResultFunc"));
8

If you're just looking for a really quick way to test code and play in the browser, you can use https://ethfiddle.com/

(Full disclosure: I'm part of the team who built it.)

I found Remix's UI to be complicated and overkill in a lot of cases, when the majority of the time all I wanted to do was 1) quickly run and test some contract code I found online, and 2) share contract code with other people without them needing to copy/paste it somewhere else in order to run it. So we built an alternative that's focused primarily on simplicity and sharing.

Here's a quick demo:

EthFiddle.com Demo

  • this is exactly what I am looking for. Thanks man.. – Code Tree Jun 23 '18 at 2:37
  • It is very concise, but it could not debug the contract. – Jim Green Jul 1 '18 at 8:19
5

If you are only interested in Solidity, Dapple, as it has been answered already, provides the best framework for unit testing.

But if you are developing in .Net / Nethereum, you can do integration tests as follow of your solidity contract:

var contract = web3.Eth.GetContract(abi, receipt.ContractAddress); var test = contract.GetFunction("test4"); Assert.True(await test.CallAsync<bool(BigInteger.Parse("3457987492347979798742")));

You will need to have deployed already your contract to your testnet. In the example above, we know the ABI already (stored in a string), and we using the the contract address of the receipt to initialise the contract.

It is also important to test the events of your contract, for example on ERC20 Transfer event can have a test like this:

var allTransfersFilter = await transfersEvent.CreateFilterAsync(new BlockParameter(3000)); var eventLogsAll = await transfersEvent.GetAllChanges<Transfer>(allTransfersFilter);

Assert.Equal(1, eventLogsAll.Count); var transferLog = eventLogsAll.First(); Assert.Equal(transferLog.Log.TransactionIndex.HexValue, transferReceipt.TransactionIndex.HexValue); Assert.Equal(transferLog.Log.BlockNumber.HexValue, transferReceipt.BlockNumber.HexValue); Assert.Equal(transferLog.Event.AddressTo, newAddress); Assert.Equal(transferLog.Event.Value, (ulong)1000);

Above we are retrieving an event, validating the transactions match, and specific event attributes match, like the address where the amount is sent and the value.

4

The simplest way to quickly test, debug a little, and play around is, IMHO, solidity-repl, since its goal is exactly quick testing of Solidity code.

I believe that project responds best to what the text of your question asks for, and to be honest I'm sensing a bias where you wrote the question with your own future answer in mind, so that you would accept it. If nothing else, the remix tag in the very question is a pretty convincing indicator. :)

So while your criteria for the "expected answer" to your own question are subjective and couldn't be questioned, I'm still leaving solidity-repl here because other people will probably come here with a similar question in mind and find that tool a better fit.

3

Firstly, I would suggest you write your code in a IDE like SublimeText. Then I would use Remix to verify that your syntax is correct, and that it will compile.

People have mentioned Truffle, but in my opinion it just changes the learning curve. Truffle uses testrpc behind the scenes which you can setup and use independently. I would suggest that you take the time to learn all the pieces of the puzzle.

All that said, testrpc only simulates functionality. I would always suggest that you test your contracts in a 'real' environment. The Ropsten test network is the best test network for this.

EthTools.com (my company built this) has a tool for submitting contracts to the chain, and then interacting with them. You can verify that your functionality works by interacting with the contract and verifying that you get the correct responses. You can do this on the ropsten test network or on the mainnet (as you see fit).

Interact with contract

Here are some videos:

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.