The Wayback Machine - https://web.archive.org/web/20240804154822/https://www.geeksforgeeks.org/how-to-test-a-smart-contract-with-remix/
Open In App

How to Test a Smart Contract with Remix?

Last Updated : 27 Sep, 2023
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report

The Remix IDE is an open-source development environment for building, testing, and deploying smart contracts on the Ethereum blockchain. One of the most notable features of Remix IDE is its integration with the Solidity programming language. Solidity is a contract-oriented language that is specifically designed for building smart contracts on Ethereum. The Remix IDE provides an intuitive interface for writing, testing, and debugging Solidity code.

What is a Smart Contract?

A smart contract is a self-executing program that runs on a blockchain network. It is essentially a digital contract that enforces the terms and conditions of an agreement between two or more parties, without the need for intermediaries like banks. Smart contracts are designed to be transparent, secure, and tamper-proof.

  • Smart contracts are typically written in a programming language such as Solidity, which is specifically designed for the Ethereum blockchain.
  • Once a smart contract is deployed on the blockchain, it becomes immutable and cannot be altered, deleted, or tampered with. 
  • This means that the terms of the contract are enforced automatically, and all parties involved can trust that the contract will be executed exactly as written.

Prerequisites

  • A Solidity compiler: Remix uses the Solidity compiler to compile your smart contract code into bytecode that can be executed on the Ethereum Virtual Machine (EVM). Fortunately, Remix also has the option to run our smart contract using its online IDE.
  • Knowledge of Solidity and Ethereum: To test your smart contract, you should have a basic understanding of Solidity and Ethereum. You should be familiar with the syntax and structure of Solidity contracts, as well as the basics of how Ethereum works.

Approach

Below are the steps to be followed to test a smart contract in Remix:

  1. Go to the Remix online IDE.
  2. Write the smart contract code.
  3. Compile the code.
  4. Deploy the contract.
  5. Test the contract.

Testing Smart Contract

This section involves testing the smart contract using 5 different approaches:

  1. Simple test example.
  2. Testing a method involving msg.sender.
  3. Testing method execution.
  4. Testing a method involving msg.value.
  5. Testing method involving msg.sender and msg.value.
  6. Testing of previously made smart contract having its own old hash

1. Simple Test Example

First, we are going through a simple test example to test our smart contract. Note that the same steps will be followed no matter what kind of testing you do.

Step 1:  First head to the Remix website where we are going to use the online Remix IDE. The remix workspace will open up and it will appear like in the image shown below.

Remix IDE

Remix IDE

Step 2: Make a solidity file: Click on the new file and enter the smart contract in the new box that appears on the left panel. Enter the smart contract name you want to make. Here, we chose “HelloWorld.sol“. 

Note: 

.sol is the extension for the solidity language in which our smart contract is being written.

Make a Solidity File

 

Step 3: Write the smart contract: We are going to write a simple Hello World smart contract in solidity in the provided workspace.

Solidity




// Basic Solidity program for Hello
// World
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
 
contract HelloWorld {
   
  string private message;
   
  constructor()
  {
    message = "Hello World!";
  }
   
  function getMessage() public view returns (string memory)
  {
    return message;
  }
   
  function setMessage(string memory newMessage) public
  {
    message = newMessage;
  }
}


Step 4: Compile the code: Head to the solidity compiler icon by clicking on it. Click the “Compile” button to make sure the code compiles without errors. This will generate the bytecode that can be deployed to the Ethereum network. You can skip this step if your auto-compile button is already switched on.

Compile the smart contract

 

Step 5: Deploy the contract: Head to the Deploy and run transactions section. The provided account is just a test id with test gas and is not real and is only meant for testing purposes. Click the “Deploy” button. You can use the Remix interface to specify the network, account, and gas settings. But you can also leave them to default.

Deploy and Run Transaction

 

Step 6: Deploy the Contract: Scroll down and you will see a deployed contract section. Click on getMessage. The following string prints as:

    0: string: Hello World!

Output

 

Step 7: Test your smart Contract: You can verify that our smart contract has been deployed correctly by seeing the transaction status at the bottom of the screen. If the operation is successful, a checkmark will be displayed next to it. You can access more detailed information by opening the transaction details. It shows details like status, transaction hash, and the amount of gas spent.

Test the smart contract

 

Hence, we have successfully tested our smart contract on Remix IDE.

2. Testing a Method involving msg.sender

To test a method that involves the msg.sender variable, you need to specify the sender address when calling the function. For example, if you have a function that sets a value for the sender, you can test it as follows:

Solidity




pragma solidity ^0.8.0;
 
contract SenderValueContract {
    mapping(address => uint) public senderValues;
     
    function setSenderValue(uint value) public {
        senderValues[msg.sender] = value;
    }
}


In the Remix IDE, specify the address of the sender by clicking on the “value” field under the “Deployed Contracts” section.

Deploy the contract

 

3. Testing Method Execution

To test the execution of a method, you need to check its return value or its effect on the state variables of the contract. For example, if you have a function that adds two integers, you can test it as follows:

Solidity




pragma solidity ^0.8.0;
 
contract AdditionContract {
    function add(uint a, uint b) public pure returns (uint) {
        return a + b;
    }
}


In the Remix IDE, call the function with some arguments and check its return value.

Input the values of a and b:

Deploy the contract

 

Output after clicking “call”:

Deploy the contract

 

4. Testing a method involving msg.value

To test a method that involves the msg.value variable, you need to specify the value of the transaction when calling the function. For example, if you have a function that accepts Ether, you can test it as follows:

Solidity




pragma solidity ^0.8.0;
 
contract DepositContract {
    mapping(address => uint) public balances;
 
    function deposit() payable public {
        balances[msg.sender] += msg.value;
    }
}


Deploy the contract

 

5. Testing method involving msg.sender and msg.value:

To test a method that involves both msg.sender and msg.value, we need to create a new function that sends some ether to the contract and checks if the sender is correctly set.
Let’s modify our previous HelloWorld contract to include a new function called payAndSayHello(), which will require the sender to send some ether to the contract and set a new message:

Solidity




// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
 
contract HelloWorld {
    string private message;
 
    constructor() {
        message = "Hello World!";
    }
 
    function getMessage() public view returns (string memory) {
        return message;
    }
 
    function setMessage(string memory newMessage) public {
        message = newMessage;
    }
 
    function payAndSayHello() public payable {
        require(msg.value > 0, "You need to send some ether");
        require(msg.sender == tx.origin, "Only externally owned accounts are allowed to call this function");
 
        message = "Hello from the sender!";
    }
}


Now, let’s test this new function by following these steps:

Step 1: Deploy the updated HelloWorld contract as described in the previous sections. In the Deploy & Run transactions section, select the payAndSayHello function from the dropdown menu and click the “transact” button.

Step 2: Verify that the transaction was successful by checking the transaction status at the bottom of the screen.

Step 3: Call the getMessage function to verify that the message has been set to “Hello Geeks”.

Deploy the contract

Step 4: Try to call the payAndSayHello function again, but this time with a value of 0. Verify that the function reverts with the error message “You need to send some ether”.

Verify the Transaction

By following these steps, we have successfully tested a method involving both msg.sender and msg.value in our smart contract.

6. Testing of previously made smart contract having its own old hash

We can also test the smart contract whose hash address is known .

Step 1: Always copy the address of the smart contract when deployed in a secure location

Step 2: Copy it from the Transactions Recorded Section

deploygeeksforgeeks

Deployed Contracts Section in Remix IDE

Step 3: Paste it in the section of At Address and click on “At Address” button.

ataddressgeeksforgeeks

Load from given address

There is no need to, again and again, deploy Smart Contract by this method.

Also, Smart Contract can be tested through Metamask accounts or default accounts :

Step 1 : Click on the Environment and select the respective wallet as Injected Provider – Metamask.

Step 2 : Select the account of Metamask

metamaskgeeksforgeeks

for Environment



Similar Reads

Steps to Execute Solidity Smart Contract using Remix IDE
Remix IDE is generally used to compile and run Solidity smart contracts. Below are the steps for the compilation, execution, and debugging of the smart contract. Step 1: Open Remix IDE on any of your browsers, select on New File and click on Solidity to choose the environment. Step 2: Write the Smart contract in the code section, and click the Comp
1 min read
How to Test a Smart Contract for Ethereum?
Public Blockchains like Ethereum are immutable, it is difficult to update the code of a smart contract once it has been deployed. To guarantee security, smart contracts must be tested before they are deployed to Mainnet. There are several strategies for testing contracts, but a test suite comprised of various tools and approaches is suitable for de
15+ min read
Steps to Create, Test and Deploy Ethereum Smart Contract
Smart contracts are self-execution programs stored on a blockchain that are automatically executed when predefined conditions are met. They allow the participants on the blockchain to transact with each other without a trusted central authority. After creating a smart contract, the next step is to deploy the smart contract onto a blockchain for exe
7 min read
Debugger - Remix
The Remix debugger is a tool that allows you to step through your Solidity code and examine the values of variables and the state of the Ethereum blockchain at different points in the execution. It is built into the Remix development environment, which is a web-based development environment for the Solidity programming language. The article focuses
9 min read
How to use GANACHE Truffle Suite to Deploy a Smart Contract in Solidity (Blockchain)?
There are various processes involved in deploying a smart contract using Ganache and Truffle Suite: 1. Install Ganache first. Ganache is a personal blockchain for Ethereum development. You must first download and install it. It is available for download from https://www.trufflesuite.com/ganache, the official website. 2. Install Truffle Suite: The n
4 min read
Creating a Smart Contract that Returns Address and Balance of Owner using Solidity
Problem: Create a smart contract named MyContract having a state variable as owner. Create a constructor to fetch the address of the owner from msg and hold it into the state variable owner. Also, create a function getBalance() to show the current balance of the owner. Solution: Every smart contract is owned by an address called as owner. A smart c
2 min read
What is Smart Contract in Solidity?
Solidity's code is encapsulated in contracts which means a contract in Solidity is a collection of code (its functions) and data (its state) that resides at a specific address on the Ethereum blockchain. A contract is a fundamental block of building an application on Ethereum. Now let's look at the code example for making smart contract : Example #
4 min read
What is Escrow Smart Contract?
Escrow is the third party that holds the asset(asset can be money, bond, or stocks) in the presence of two parties. Escrow will release the fund when certain conditions are met. For Example: "A" is a seller and wants to sell his car, and "B" is a buyer who wants to buy "A"'s car so they will contact Escrow "C"(an arbiter) which holds the asset unti
2 min read
How to use MetaMask to Deploy a Smart contract in Solidity (Blockchain)?
Smart contracts are self-executing contracts. They were first proposed by Nick Szabo in the 90s. They are set of rules and protocols which two parties agree upon and have to follow. One of the main features is that they are immutable once deployed on the blockchain. It is widely used in the Ethereum blockchain. The main language used for writing sm
3 min read
Interacting With Ethereum Smart Contract Using Web3js
Ethereum is a cryptocurrency platform in the market just like Bitcoin. It is an open-source & decentralized blockchain featuring working on smart contracts. It has its own cryptocurrency known as ether. The smart contracts in Ethereum are written in solidity. TestRPC The Ethereum TestRPC is like a manual emulator for blockchain. It provides blo
4 min read
three90RightbarBannerImg