7

I've written some truffle tests that interact with the account balances. Example:

A contract transfers X amount of ether from account A to account B.

Surprisingly the state of the accounts (especially the balances) are not reset between test cases. Meaning tests that test balance transfers cannot be deterministic. Is there a way around this?

2 Answers 2

5

When running Truffle JavaScript tests using Ganache or ganache-cli, there is nothing to do: Truffle resets the blockchain state between each test. The initial snapshot is done just after loading the contracts.

More precisely, the state is reset before each contract (Truffle replacement for mocha's describe). For example:

var MyContract = artifacts.require("./MyContract.sol");

contract('MyContract - A', function(accounts) {
  before("Setup", async function () {
    // Suppose balance of accounts[0] == 100ETH
  });

  it("should do Alpha", async function() {
    // Balance of accounts[0] == 100ETH
    decreaseAcount0By1ETH();
    // Balance of accounts[0] == 99ETH
  });

  it("should do Beta", async function() {
    // Balance of accounts[0] == 99ETH,
    // because state is *not* reset between 'it'
  });

contract('MyContract - B', function(accounts) {
  it("should do Alpha", async function() {
    // Balance of accounts[0] == 100ETH again,
    // because state is reset between 'contract'
  });
});

This is something you can track in Ganache logs. Look for evm_snapshot and evm_revert.

2
  • 1
    The documentation for Truffle's Clean Room testing was moved to here May 28, 2022 at 12:43
  • Fixed! Thank you @JimmyBosse for pointing this out.
    – philippe_b
    Jun 3, 2022 at 7:57
4

Yeah, if you want deterministic tests you need to use testrpc with some special params before each test.

Something like:

let web3 = new Web3('ws://localhost:8546');
let testrpc;

before(function(done) {
  testrpc = TestRPC.server({
    ws: true,
    gasLimit: 5800000,
    total_accounts: 10,
    seed: 1
  });

  testrpc.listen(8546, '127.0.0.1');
  done();
});

More info at: https://github.com/ethereumjs/testrpc

2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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