unit testingUnit tests are built into the language and are used to test the contract functions individually. These tests work well when little context is required. However, they cannot test chain interactions - like sending accounts
$NEAR tokens - since they need to be processed by the network.We use
near-sandbox to start a local blockchain and near-api to deploy contracts, submit transactions, and read state. These tests run locally without a testnet account.
Account Creation
The first thing our test does is to create multiple accounts with 10$NEAR tokens each and deploy the contract to one of them.
test_basics.rs
cargo_near_build to compile the contract before deploying it to the sandbox, so we do not need to pre-compile it ourselves.
Contract Initialization
The test reads the sandbox’s block timestamp and setsend_time to 60 seconds later. It then deploys the contract and calls init in the same transaction.
test_basics.rs
Time is a StringThe
U64 timestamp is passed as a String to preserve all 64 bits when serialized as JSON.Bidding
Now that the contract is deployed and initialized, we can start bidding and checking if the contract behaves as expected. We first makealice place a bid of 1 NEAR, and check that the contract correctly registers the bid. Then, we have bob place a bid of 2 NEAR, and check that the highest bid is updated, and that alice gets her NEAR refunded.
test_basics.rs
Checking the balance
It is important to notice how we check ifalice was refunded. We query her balance after her first bid, and then check if it has increased by 1 NEAR after bob makes his bid.
You might be tempted to check if alice’s balance is exactly 10 NEAR after she gets refunded, but alice balance cannot be 10 NEAR anymore, because some $NEAR was consumed as gas fees when alice called bid.
Testing invalid calls
When testing we should also check that the contract does not allow invalid calls. The next part checks that the contract doesn’t allow for bids with fewer$NEAR tokens than the previous to be made.
test_basics.rs
Fast Forwarding Time
The sandbox allows us to fast-forward time, which is useful for testing the contract when the auction is over. The test advances 200 blocks in order to pass a minute, and thus allowing the auction to be claimed. After which the auction can now be claimed. Once claimed the test checks that the auctioneer has received the correct amount of$NEAR tokens.
test_basics.rs
Executing the tests
Now that we understand what we are testing, let’s go ahead and run the tests!Conclusion
In this part of the tutorial, we’ve seen how to use our sandbox testing environment to test the contract. We’ve tested the contract’s initialization, bidding, and time advancement. You are now ready to move to the next section, where we will deploy the contract totestnet and interact with it through the CLI.