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
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.
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
In Solidity, we’re going to write unit tests and integration tests for our smart contracts. Let’s start with unit tests since they’re the simpler of the two.
Here’s our first unit test: TestBackground
:
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:
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:
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
In JavaScript, we write an integration test to make sure the contracts act as we expect, so that we can build a DApp which uses them.
Here’s our JavaScript test, 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.