QA InfoTech , Independent Software Testing Service Logo
jobs@qainfotech.com
Sales: Contact Sales +1 469-759-7848 sales@qainfotech.com
QA Infotech your Software testing partner
Menu
  • About
    • Team
    • Overview
    • Values and Culture
    • QA InfoTech Foundation
    • Careers
  • Services
    • QUALITY ASSURANCE

      • Functional Testing
      • Automation Testing
      • Mobile Testing
      • Performance Testing
      • Accessibility Testing
      • Usability Testing
      • Security Testing

      Quality Engineering

      • Globalization, Translation & Localization Testing
      • Courseware & Content Testing
      • Crowdsourced Testing
      • Cloud Testing

      Digital Assurance

      • Digital Assurance
      • Data Sciences & Analytics
      • Quality Consulting & Test Center of Excellence (TCOE)
      • SAP Testing
      • Selenium Test Automation
  • Verticals
    • e-learning
      List Start
    • e-Learning
    • Publishing
    • BFSI
    • health
    • Health Care
    • Media
    • Travel
    • retail-min
    • Retail
    • Government
    • OpenERP
    • List Stop
  • Knowledge Center
    • Case Studies
    • White Paper
    • Webinars
    • Blogs
  • WebinarNew
  • News
    • News
    • Press Release
  • Contact
  • Get A Quote
QA InfoTech »
The Ultimate Guide To Test Your Solidity Smart Contracts
23 Oct, 2019

The Ultimate Guide To Test Your Solidity Smart Contracts

  • Oshin Gupta
  • Blockchain,Blogs
  • Tags: Blockchain, Cryptocurrency, Smart Contract Audits
  • no comments

When we hear about blockchain technology, we mainly think of either the cryptocurrencies or the smart contracts. Initially, it was about the cryptocurrencies when Bitcoin gained the market attention and the crypto world came to boom. But, then blockchain technology is not all about just cryptocurrencies, it is more about immutable distributed ledger for digital assets (which can be defined through smart contracts). The major use cases of the blockchain are KYC (Know Your Customer), SCM (Supply Chain Management), Medical Record Keeping, Energy Trading, Crowdfunding, etc.

Smart Contract Developers can develop the contract and perform manual testing. This is for beginner level only; it does not make sense to develop an application and deploy it on production without performing any testing. And it is quite mandatory for the situation as once you deploy the contract, you can’t modify it.

This can be achieved only by deploying a modified contract which will result in a new contract address; if you refer to the new address then you will lose all the data stored in the previous contract. One way to do this is to use the Upgradable Smart Contract approach, but it’s not really a good idea to upgrade the contract for every single bug. It’s better to perform testing operations for your smart contract thoroughly so a contract once deployed need not be modified.

In this blog post, we will be talking about the smart contract testing using truffle framework. Smart contract test cases can be written using solidity and Javascript/typescript. We will focus on Javascript test cases using async/await. One can write the test cases using .then function as well.

The blog is written with an assumption that you have a basic understanding of smart contract development using solidity and the truffle framework. If not, you can first go through the solidity documentation and our truffle framework blog or truffle documentation for reference. For this tutorial, we will be using the simple Coin contract provided as an example in the solidity documentation.

Preparations:

Truffle Setup:  I am assuming you are done with the truffle setup using the truffle init command. If not, you can follow the truffle documentation.

Prepare Contract File: Create a contract file in the /contracts directory naming Coin.sol. The contract code is given below:


pragma solidity >=0.5.0 <0.7.0; contract Coin {    // The keyword "public" makes variables    // accessible from other contracts    address public minter;    mapping (address => uint) public balances;




   // Events allow clients to react to specific

   // contract changes you declare

   event Sent(address from, address to, uint amount);




   // Constructor code is only run when the contract

   // is created

   constructor() public {

       minter = msg.sender;

   }




   // Sends an amount of newly created coins to an address

   // Can only be called by the contract creator

   function mint(address receiver, uint amount) public {

       require(msg.sender == minter, "Unauthorized Access");

       require(amount < 1e60, "Amount limit exceeded");

       balances[receiver] += amount;

   }




   // Sends an amount of existing coins

   // from any caller to an address

   function send(address receiver, uint amount) public {

       require(amount <= balances[msg.sender], "Insufficient balance");

       balances[msg.sender] -= amount;

       balances[receiver] += amount;

       emit Sent(msg.sender, receiver, amount);

   }

}

In the contract defined above, one can use modifiers as well. For now, we are just keeping it simple. There are two functions mint and send defined in the contract. The Mint function can be called by the minter or contract creator only to transfer coins to the receiver address and the Send function can be called by any address who has sufficient balance to transfer coins to any other address.

Let’s write the test cases using javascript

Truffle framework is built on top of mocha and uses chai for assertions. If you are not familiar with writing tests in mocha, you can follow the mocha and chai documentation.

Let’s first create a file under /test directory naming coinTest.js. (Note: Keep in mind while creating a test file that it should end with the Test keyword, otherwise your test will not be executed for that file)

Contract abstraction can be used for making contract interaction possible from javascript; we can do so by requiring the contract artefacts (make sure you require the artefacts using the contract name, not the file name) by using the following code:

const Coin = artifacts.require("Coin");

In truffle, we will use contract() instead of describe(). Accounts can be accessed through the accounts parameter (defined in the code below). Let’s define some variables which we will be using in the test cases. Also, define the beforeEach hook for deploying the new smart contract before executing each test case.

contract("Coin", accounts => {
   let owner = accounts[0];
   let instance;
   let amount = 1000;
   let transferAmount = 500; 
   beforeEach(async function () {
       instance = await Coin.new({ from: owner });
   });
})

Now, we will start writing the test cases for constructor, mint and send function. Test cases include scenarios such as, to test minter’s account, to test minter’s balance, to test mint function for minter’s account or with some other account, to test send function for sufficient and insufficient balance. The complete test file is given below:

 const Coin = artifacts.require("Coin");
 
contract("Coin", accounts => {
 
   let owner = accounts[0];
   let instance;
   let amount = 1000;
   let transferAmount = 500;
 
   beforeEach(async function () {
       instance = await Coin.new({ from: owner });
   });
 
   it("should check owner account as minter", async () => {
       let minter = await instance.minter();
       assert.equal(
           minter,
           owner,
           "Owner Account is not the minter"
       );
   });
 
   it("should check minter's balance", async () => {
       let balance = await instance.balances(owner);
       assert.equal(
           balance.valueOf(),
           0,
           "Minter's Coin balance is non-zero"
       );
   });
 
   it("should check second account balance", async () => {
       let balance = await instance.balances(accounts[1]);
       assert.equal(
           balance.valueOf(),
           0,
           "Second Account Coin balance is non-zero"
       );
   });
 
   it("should mint 1000 Coins to second account", async () => {
       await instance.mint(accounts[1], amount, { from: owner });
       let balance = await instance.balances(accounts[1]);
       assert.equal(
           balance.valueOf(),
           amount,
           "Second Account's Coin balance is not equal to the minting amount"
       );
   });
 
   it("should throw if mint is called not from minter account", async () => {
       try {
           await instance.mint(accounts[2], amount, { from: accounts[1] });
       } catch (error) {
           assert.throws(() => { throw new Error(error) }, Error, "Unauthorized Access");
       }
   });
 
   it("should transfer 500 Coins from third account to second account", async () => {
       try {
           await instance.send(accounts[1], transferAmount, { from: accounts[2] });
       } catch (error) {
           assert.throws(() => { throw new Error(error) }, Error, "Insufficient balance");
       }
   });
 
   it("should transfer 500 Coins from second account to third account", async () => {
       await instance.mint(accounts[1], amount, { from: owner });
       await instance.send(accounts[2], transferAmount, { from: accounts[1] });
       let secondAccBalance = await instance.balances(accounts[1]);
       let thirdAccBalance = await instance.balances(accounts[2]);
       assert.equal(
           secondAccBalance.valueOf(),
           amount - transferAmount,
           "Second Account's Coin balance is not equal to transfer amount"
       );
       assert.equal(
           thirdAccBalance.valueOf(),
           transferAmount,
           "Third Account's Coin balance is not equal to transfer amount"
       );
   });
});


Running Test File:

Truffle provides a clean-room environment for running the test cases. When running your tests against Ganache or Truffle Develop, Truffle will use advanced snapshotting features to ensure that test files don’t share state with each other. When running against other Ethereum clients like go-ethereum, Truffle will re-deploy all of your migrations at the beginning of every test file to ensure you have a fresh set of contracts to test against.

We will be using truffle develop to run the test cases; one can connect to any of the ethereum networks using truffle console. Or one can run the truffle test command as well, by defining the connection details in the truffle config file.
Start by opening the develop console using the command:

$ truffle develop

It will start the ethereum node at http://127.0.0.1:9545 port and list the default 10 accounts along with the private keys in the console. To run the test file either you can simply run,

> test

or to run the specific test file you can run

> test /path/to/test/file (In our case, run test /test/coinTest.js)

The result is shown below:

This blog defines a simple procedure that one can follow to test their smart contracts. Balance project efforts, costs and timeline between development and testing your contract, because remember “All code is guilty until proven innocent”.

Site Categories

  • Accessibility Testing (25)
  • Automation Testing (22)
  • Banking Application Testing (2)
  • Blockchain (2)
  • Blogs (299)
  • Case Studies (30)
  • Cloud Testing (2)
  • Compatibility Testing (1)
  • E-Learning testing (2)
  • Functional Testing (3)
  • Healthcare App Testing (8)
  • Innovation (5)
  • Job Openings (27)
  • Mobile Testing (11)
  • News (139)
  • News & Updates (7)
  • Our-Team (6)
  • Performance Testing (19)
  • Press Releases (37)
  • QA Thought Leadership (1)
  • Security Testing (12)
  • Software Testing (31)
  • Testimonials (23)
  • Translation & Globalization Testing (9)
  • Uncategorized (4)
  • Usability Testing (1)
  • Webinars (20)
  • White Papers (33)
  • Popular
  • Recent
  • Tags
  • Effective Regression Testing Strategy for Localized Applications Effective Regression Testing Strategy for Localized Applications March 23, 2015
  • Moving from a commercial to an open source performance testing tool August 12, 2015
  • An Increased Appreciation for Software Localization An Increased Appreciation for Software Localization October 8, 2014
  • What is that one compelling reason for crowd sourced testing? What is that one compelling reason for crowd sourced testing? December 24, 2014
  • Nuances of education technology testing Nuances of education technology testing February 21, 2016
  • IoT Security: Are We 2020 Ready? November 25, 2019
  • UI/UX Designer November 20, 2019
  • Business Development Executive for Phando November 20, 2019
  • React Js Developer November 20, 2019
  • Performance Engineer November 20, 2019
  • Jobs - 9
  • Hiring - 9
  • performance testing - 6
  • accessibility-testing - 6
  • #AccessibilityTesting - 6
  • #PerformanceTesting - 6
  • accessibility - 4
  • mobile app testing - 4
  • automation testing - 4
  • #PerformanceTestingServices - 4
  • mobile - 3
  • testing - 3
  • functional testing - 3
  • agile cycle - 3
  • DevOps - 3
  • performance - 3
  • software testing services - 3
  • data analytics - 3
  • #SoftwareTesting - 3
  • #TestAutomation - 3
  • #AppSecurity - 3
  • #SecureBankingApps - 3
  • #TestingBankingApplications - 3
  • #SoftwareTestingStrategy - 3
  • #SoftwareTestAutomation - 3

Site Archives

  • November 2019 (11)
  • October 2019 (8)
  • September 2019 (10)
  • August 2019 (6)
  • July 2019 (4)
  • June 2019 (7)
  • May 2019 (18)
  • April 2019 (15)
  • March 2019 (5)
  • February 2019 (1)
  • January 2019 (5)
  • December 2018 (3)
  • October 2018 (4)
  • August 2018 (4)
  • July 2018 (15)
  • June 2018 (1)
  • May 2018 (3)
  • April 2018 (7)
  • March 2018 (5)
  • February 2018 (15)
  • January 2018 (3)
  • December 2017 (8)
  • November 2017 (13)
  • October 2017 (20)
  • September 2017 (13)
  • August 2017 (8)
  • July 2017 (7)
  • June 2017 (6)
  • May 2017 (5)
  • April 2017 (1)
  • March 2017 (6)
  • January 2017 (3)
  • December 2016 (7)
  • October 2016 (3)
  • September 2016 (3)
  • August 2016 (6)
  • July 2016 (4)
  • June 2016 (3)
  • May 2016 (6)
  • April 2016 (3)
  • March 2016 (7)
  • February 2016 (3)
  • January 2016 (2)
  • December 2015 (7)
  • November 2015 (2)
  • October 2015 (7)
  • September 2015 (4)
  • August 2015 (2)
  • July 2015 (14)
  • June 2015 (2)
  • May 2015 (2)
  • April 2015 (5)
  • March 2015 (9)
  • February 2015 (11)
  • January 2015 (4)
  • December 2014 (3)
  • November 2014 (4)
  • October 2014 (6)
  • September 2014 (7)
  • August 2014 (6)
  • July 2014 (7)
  • June 2014 (6)
  • May 2014 (4)
  • April 2014 (7)
  • March 2014 (7)
  • February 2014 (8)
  • January 2014 (6)
  • December 2013 (3)
  • November 2013 (6)
  • October 2013 (6)
  • September 2013 (8)
  • August 2013 (3)
  • July 2013 (4)
  • June 2013 (6)
  • May 2013 (3)
  • April 2013 (3)
  • March 2013 (3)
  • February 2013 (2)
  • January 2013 (1)
  • December 2012 (2)
  • November 2012 (3)
  • October 2012 (3)
  • September 2012 (5)
  • August 2012 (2)
  • July 2012 (6)
  • June 2012 (1)
  • May 2012 (2)
  • April 2012 (3)
  • March 2012 (8)
  • February 2012 (4)
  • January 2012 (3)
  • December 2011 (1)
  • November 2011 (4)
  • October 2011 (3)
  • September 2011 (2)
  • August 2011 (3)
  • June 2011 (4)
  • May 2011 (1)
  • April 2011 (4)
  • February 2011 (1)
  • January 2011 (1)
  • October 2010 (2)
  • August 2010 (4)
  • July 2010 (2)
  • June 2010 (3)
  • May 2010 (3)
  • April 2010 (1)
  • March 2010 (5)
  • February 2010 (1)
  • January 2010 (2)
  • December 2009 (3)
  • November 2009 (1)
  • October 2009 (2)
  • July 2009 (1)
  • June 2009 (2)
  • May 2009 (2)
  • March 2009 (2)
  • February 2009 (4)
  • December 2008 (2)
  • November 2008 (1)
  • October 2008 (1)
  • September 2008 (1)
  • August 2008 (2)
  • May 2008 (1)
  • February 2008 (1)
  • September 2007 (1)
  • August 2007 (1)
  • May 2007 (2)
  • June 2006 (1)

Tag Cloud

#AccessibilityTesting #AI #AppPerformance #AppSecurity #AutomatedTesting #AutomationTesting #BigDataTesting #DigitalAssurance #ImageScreenReader #InteractiveAccessibility #MobileAppTesting #MobileTesting #PerformanceTesting #PerformanceTestingServices #ScreenReaderAccessibilityTesting #ScreenReaderTesting #SecureBankingApps #SoftwareQualityAssurance #SoftwareTestAutomation #SoftwareTesting #SoftwareTestingStrategy #TestAutomation #TestingBankingApplications #UsabilityTestingWithScreenReader accessibility accessibility-testing agile cycle automation automation testing BigData data analytics DevOps functional testing Hiring Jobs localization testing mobile mobile app testing Offshore QA Testing performance performance testing Selenium Test Automation software testing services testing xAPI

Post Calendar

December 2019
M T W T F S S
« Nov    
 1
2345678
9101112131415
16171819202122
23242526272829
3031  

About QA InfoTech

Q A QA InfoTech is a C M M i CMMi Level III and I S O ISO 9001: 2015, I S O ISO 20000-1:2011, I S O ISO 27001:2013 certified company. We are one of the reputed outsourced Q A QA testing vendors with years of expertise helping clients across the globe. We have been ranked amongst the 100 Best Companies to work for in 2010 and 2011 & 50 Best Companies to work for in 2012 , Top 50 Best IT & IT-BMP organizations to work for in India in 2014, Best Companies to work for in IT & ITeS 2016 and a certified Great Place to Work in 2017-18. These are studies conducted by the Great Place to Work® Institute. View More

Get in Touch

Services

  • Functional Testing
  • Automation Testing
  • Mobile Testing
  • Performance Testing
  • Accessibility Testing
  • Security Testing
  • Localization Testing
  • Cloud Testing
  • Quality Consulting

Useful Links

  • Blogs
  • Downloads
  • Case Studies
  • Webinars
  • Team
  • Pilot Testing
  • Careers
  • QA TV
  • Contact

Office Locations

Michigan, USA
Arkansas, USA
Noida, INDIA ( HQ )
Bengaluru, INDIA
Michigan, USA

  • 32985 Hamilton Court East, Suite 121, Farmington Hills, Michigan, 48334
  • +1-469-759-7848
  • info@qainfotech.com

Arkansas, USA

  • Rain Tree Business Center, 900B South Walton Blvd, Suite 1, Bentonville, Arkansas, 72712
  • +1-248-246-1109
  • info@qainfotech.com

Noida, INDIA ( HQ )

  • A-8, Sector 68 Noida, Uttar Pradesh, 201309
  • +91-120-6101-805 / 806
  • info@qainfotech.com

Bengaluru, INDIA

  • RMZ Ecoworld, Outer Ring Road, Bellandur, Bengaluru, Karnataka, 560103
  • +91-95600-00079
  • info@qainfotech.com

Copyright ©2019 qainfotech.com. All rights reserved | Privacy Policy | Disclaimer

Scroll
QA InfoTech logo
  • About
    ▼
    • Team
    • Values and Culture
    • Overview
    • QA InfoTech Foundation
    • Careers
  • Services
    ▼
    • Functional Testing Services
    • Automation Testing Services & Tools
    • Mobile Testing Services
    • Performance Testing Services
    • Accessibility Testing Services
    • Usability Testing
    • Security Testing
    • Translation & Globalization Testing Services
    • Courseware & Content Testing
    • Crowdsourced Testing
    • Cloud Testing
    • Digital Assurance
    • Data Sciences and Analytics
    • SAP Testing
    • Selenium Test Automation
  • Verticals
    ▼
    • e-Learning
    • Health Care
    • Retail
    • Publishing
    • Media
    • Government
    • BFSI
    • Travel
    • OpenERP
  • Knowledge Center
    ▼
    • Case Studies
    • White Paper
    • Webinars
    • Blogs
  • News
    ▼
    • News
    • Press Release
  • Contact
  • Get a Quote
We use cookies to ensure that we give you the best experience on our website. If you continue to use this site we will assume that you are happy with it.Accept CookiesPrivacy policy