Generative Data Intelligence

How to Test Ethereum Smart Contracts

Date:

The full working project code can be found on Github

We have two smart contracts: Background and EntryPoint.

Background is an internal contract that our DApp front-end doesn’t interact with. EntryPoint is the contract which is designed for our DApp to interact with. It references Background in its code.

The smart contracts

Figure 2: Background.sol

Above, we see our Background contract. It exposes three functions: storeValue(uint), getValue(uint), and getNumberOfValues(). All these functions have simple instructions, so they’re easy to unit test.

Figure 3: EntryPoint.sol

This is our EntryPoint contract. An address for our Background contract is injected into the constructor and used as a state variable, named backgroundAddress. EntryPoint exposes three functions: getBackgroundAddress(), storeTwoValues(uint, uint), and getNumberOfValues().

storeTwoValues(uint, uint) calls a function in the Background contract twice, so unit testing this function in isolation will prove difficult. The same goes for getNumberOfValues(). These are good cases for integration tests.

Solidity

Here’s our first unit test: TestBackground:

Figure 4: TestBackground.sol

It tests our Background contract to make sure it:

  • Stores a new value in its values array.
  • Returns values by their index.
  • Stores multiple values in its values array.
  • Returns the size of its values array.

This is TestEntryPoint, with a unit test called testItHasCorrectBackground() for our EntryPoint contract:

Figure 5: TestEntryPoint.sol

This function tests the dependency injection. As mentioned earlier, the other functions in our EntryPoint contract require interaction with Background so we cannot test them in isolation.

These functions are tested in our integration tests:

Figure 6: Solidity Integration test

We can see that TestIntegrationEntryPoint uses an extension of Background called BackgroundTest , defined on line 43, to act as our mock contract. This enables our tests to check if EntryPoint calls the correct functions in the backgroundAddress contract it references.

Javascript test files

Here’s our JavaScript test, entryPoint.test.js:

Figure 7: entryPoint.test.js

Using the functions available in our EntryPoint contract, the JavaScript tests ensure that values from outside the Blockchain can be sent to the smart contract by creating transactions targeting the storeTwoValues(uint, uint) function (line 15). Retrieving the number of values stored on the Blockchain by calling getNumberOfValues() on lines 12 and 16 of the tests ensure that they get stored.

Source: https://medium.com/better-programming/how-to-test-ethereum-smart-contracts-35abc8fa199d?source=rss——-8—————–cryptocurrency

spot_img

Latest Intelligence

spot_img

Chat with us

Hi there! How can I help you?