Skip to content

Instantly share code, notes, and snippets.

@gsans
Created February 25, 2022 12:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gsans/86152bc533c443fbce7352f9f485fdc1 to your computer and use it in GitHub Desktop.
Save gsans/86152bc533c443fbce7352f9f485fdc1 to your computer and use it in GitHub Desktop.
Solidity unit test
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.10;
// This import is automatically injected by Remix
import "remix_tests.sol";
// This import is required to use custom transaction context
// Although it may fail compilation in 'Solidity Compiler' plugin
// But it will work fine in 'Solidity Unit Testing' plugin
import "remix_accounts.sol";
import "../hello-world.sol";
// File name has to end with '_test.sol', this file can contain more than one testSuite contracts
contract testSuite {
/// 'beforeAll' runs before all other tests
/// More special functions are: 'beforeEach', 'beforeAll', 'afterEach' & 'afterAll'
function beforeAll() public {
// <instantiate contract>
Assert.equal(uint(1), uint(1), "1 should be equal to 1");
}
function checkSuccess() public {
// Use 'Assert' methods: https://remix-ide.readthedocs.io/en/latest/assert_library.html
Assert.ok(2 == 2, 'should be true');
Assert.greaterThan(uint(2), uint(1), "2 should be greater than to 1");
Assert.lesserThan(uint(2), uint(3), "2 should be lesser than to 3");
}
function checkSuccess2() public pure returns (bool) {
// Use the return value (true or false) to test the contract
return true;
}
function checkFailure() public {
Assert.notEqual(uint(1), uint(2), "1 should not be equal to 2");
}
/// Custom Transaction Context: https://remix-ide.readthedocs.io/en/latest/unittesting.html#customization
/// #sender: account-1
/// #value: 100
function checkSenderAndValue() public payable {
// account index varies 0-9, value is in wei
Assert.equal(msg.sender, TestsAccounts.getAccount(1), "Invalid sender");
Assert.equal(msg.value, 100, "Invalid value");
}
}
contract MyTest {
HelloWorld greeting;
// beforeEach works before running each test
function beforeEach() public {
greeting = new HelloWorld();
}
/// Test if initial greeting is set correctly
function initialMessage() public returns (bool) {
return Assert.equal(greeting.get(), "Hello world!", "initial greeting is not correct");
}
/// Test if greeting is set as expected
function messageChanges() public returns (bool) {
greeting.set("Hello Confoo 2022!");
return Assert.equal(greeting.get(), "Hello Confoo 2022!", "greeting is not right");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment