LoginSignup
0
0

More than 3 years have passed since last update.

Truffleの単体テストでモック的にERC20を利用する方法

Posted at

経緯

下記のような関数の単体テストを実行するために、ERC20のモックが必要になった。その手法を備忘録的に記述

pragma solidity ^0.5.0;

import "openzeppelin-solidity/contracts/token/ERC20/ERC20Mintable.sol";
import "openzeppelin-solidity/contracts/math/SafeMath.sol";

contract HogeContract {
    using SafeMath for uint256;

    mapping(address => uint256) amap;

    function huge(address _token, uint256 value) public {
        amap[_token] += value.div(ERC20(_token).totalSupply());
    }
}

やり方

1.contractsフォルダ以下にTestErc20Token.sol(名前は任意)ファイルを作成する。
2.1に下記の内容を記述する。
 ・solidityバージョンは任意
 ・openzeppelinがインストールされていない場合は別途インストールが必要
 ・発行数や名前、小数点桁数は任意

pragma solidity ^0.5.0;

import "openzeppelin-solidity/contracts/token/ERC20/ERC20.sol";

contract TestErc20Token is ERC20 {
    string public name = "TestErc20Token";
    string public symbol = "T20T";
    uint public decimals = 18;
    constructor() public {
        _mint(msg.sender, 100000000);
    }
}

3.testフォルダ以下にHogehoge.ts(名前は任意)ファイルを作成する。
4.3に下記の内容を記述する(あくまで例)

contract('HogeContractTest', ([deployer, u1, u2]) => {
    const hogeTestContract = artifacts.require('HogeContract')
    const testErc20TokenContract = artifacts.require('TestErc20Token')
    describe('HogehogeTest; huge', () => {
        it('huge', async () => {
            const hogeContractTest = await hogeTestContract.new()
            const erc20 = await testErc20TokenContract.new()
            hogeContractTest.huge(erc20.address, 5)
         // 以下assertを書いていく
        })
    })
})

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0