Set Up and Test a Smart Contract in Solidity

Noah Hein
InstructorNoah Hein
Share this video with your friends

Social Share Links

Send Tweet

We will use the Test.sol smart contract that Forge provides to turn your smart contract into something that can be tested. We'll configure the file using the setup function and successfully run our test suite.

Instructor: [0:02] Here you can see that we're in our test folder. We're looking in Contract.t.sol. You can see it looks just like our other smart contract file where we declared the Solidity version. [0:17] Here you can see that we are importing the Test.sol smart contract, which we are inheriting on our contract test by using is Test. This contract test has all the functionality that the Forge Standard Library provides through this test smart contract.

[0:36] Here you can see it has a function called setUp(). SetUp is run once at the beginning of each test suite. You can do any configuration that you need in this setUp function. To get that setUp, we're going to need to import our Contract.sol file. Then what we can do is with that imported, we can say that we've got a number contract, and we're going to put that in the variable number.

[1:08] Then in the setUp, we can say that number is equal to a new number and will declare 10 as the beginning variable there or the beginning value for our smart contract.

[1:20] Now you can see if we run our file here, we save it, and then we open up a terminal, we run forge test, that everything is still running, and we've got an OK. You can see that we've got this test example, it will go through Forge, will go through every single function, and if it has a test prefix, it will test it and it will expect an assertion to be true here.

[1:48] We can go ahead and quickly check to make sure that everything is still working by making that fail. Now you can see that our test suite will fail.

[1:57] With that, we can delete this test example function, and we'll go ahead and create a new function called testIcrement(), and testIcrement should be a public function. For this, what we want to do is we want to call the getNum because we want to track that. We'll do number.getNum() and will store that in that contract number variable and then we can call number.increment.

[2:27] Now we can expect there to be a difference here between number.getNum(), because that should return 11 now, and contract.num will be 10.

[2:36] We can see if we do assertEq(). This will take two parameters and compare the two. We'll say we would expect contractNum +1 = number.getNum. We can go ahead and run that, make sure that all of this is working. We run forge test. You could see we are getting a passing test result.