Testing by Example

Testing Smart Contracts in Q-Remix

Q-Remix supports writing and running Solidity unit tests directly within your workspace using a Remix-compatible test runner. This guide walks you through the basics of writing smart contract tests, setting up your test environment, and using advanced features like multiple accounts and error handling.

File Structure

All test files should end with _test.sol and reside in the same directory or a dedicated tests/ folder. For example:

contracts/ │ ├── MyContract.sol ├── MyContract_test.sol

Writing Your First Test

Contract: SimpleStorage.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

contract SimpleStorage {
    uint public storedData = 42;

    function set(uint x) public {
        storedData = x;
    }

    function get() public view returns (uint) {
        return storedData;
    }
}

Test: SimpleStorage_test.sol

Handling Reverts and Errors

Use try-catch blocks to assert that a transaction should revert with a specific reason.

Common Assertions

Function
Description

Assert.equal(a, b, msg)

Check if a == b

Assert.notEqual(a, b, msg)

Check if a != b

Assert.ok(condition, msg)

Check if condition == true

Assert.isFalse(condition, msg)

Check if condition == false

Tips

  • Always use beforeEach() or beforeAll() to set up fresh instances.

  • Use #sender: annotations for testing with different accounts.

  • Prefer testing both success and failure paths for better coverage.

  • Keep test names descriptive: shouldFailIf, shouldRevertWhen, returnsExpectedResult, etc.

Advanced Topics

  • Testing imported contracts from GitHub (e.g., OpenZeppelin)

  • Mocking and faking behavior

  • Custom event assertions (via logs)

📎 For event testing and full debugging, check the Q-Remix logs and console panel.

Last updated