[Ethereum] unit test with truffle, solidity or mocha

mochasolidityunittesting

Truffle allows either one or the other. Now I wonder which I shall use to test my code. I'm not a big fan of mocha. When I see code like

contract('MetaCoin', function(accounts) {   it("should put 10000 MetaCoin in the first account", function() {
    return MetaCoin.deployed().then(function(instance) {
      return instance.getBalance.call(accounts[0]);
    }).then(function(balance) {
      assert.equal(balance.valueOf(), 10000, "10000 wasn't in the first account");
    });

I think that something went really wrong in terms of readability. On the other hand the idea to write a contract to test another contract makes me pretty unconfortable. Which are the caveats of unit testing with these two different approaches?

Best Answer

I have written more than a thousand tests for different smart contracts and can say that you will almost always want to use javascript/mocha with truffle. There are very few cases that I have run into where you will want to use solidity instead. It is just so much easier to setup your contracts to the state that you want in order to run the tests.

Also... you really don't need to chain up function calls like in the example given. You can use async/await which will make things MUCH cleaner and readable. I have created a boilerplate truffle project which I use for any of my new projects. I keep it updated with examples etc. I would highly recommend checking out the way tests are in there...

repo:

https://github.com/TovarishFin/smart-contract-boilerplate

direct link to a test file using async/await:

https://github.com/TovarishFin/smart-contract-boilerplate/blob/master/test/ExampleCoin.js

Related Topic