54

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?

8 Answers 8

52

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

3
  • 2
    Is there a way to "console.log" stuff?
    – manidos
    Commented Jul 27, 2016 at 14:06
  • 3
    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
    Commented Jul 28, 2016 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
    Commented Aug 26, 2017 at 7:59
20

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.

4
  • IMHO This allows for real unit testing as opposed to integration testing with your rpc client. Commented Apr 10, 2016 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
    Commented Apr 10, 2016 at 19:10
  • OP is not asking about unit testing, why don't you use Truffle or Embark?
    – niksmac
    Commented Apr 11, 2016 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
    Commented Apr 11, 2016 at 3:28
17

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);
  });
});
1
  • 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
    Commented Apr 10, 2016 at 19:08
14

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

3
  • this is exactly what I am looking for. Thanks man..
    – Code Tree
    Commented Jun 23, 2018 at 2:37
  • It is very concise, but it could not debug the contract.
    – Jim Green
    Commented Jul 1, 2018 at 8:19
  • thats awesome! unfortunately it no longer seem to work - its stuck at "compiling" and doesnt offer the functions to call.
    – Tim
    Commented Oct 9, 2022 at 8:27
12

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"));
1
  • Nice. Have to check this out. Commented Apr 10, 2016 at 22:40
8

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.

1
  • Thanks (upvoted). This Q&A was written after several answers to other questions made me realize there was repetition into explaining how Remix could be used to answer a variety of questions and it lacked clearer documentation :)
    – eth
    Commented Dec 26, 2019 at 7:10
7

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.

5

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 and acknowledge you have read our privacy policy.

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