I'm learning Truffle framework. I have created one sample contract MyToken

pragma solidity ^0.4.17;

contract MyToken{

    mapping(address => uint) balanceOf;
    event valueLogger(uint);
    event addressLogger(address);

    constructor (uint _initalSupply) public payable{
        balanceOf[msg.sender] = _initalSupply;

    function BalanceOf(address _address) view public returns(uint){
       return balanceOf[_address];

    function Transfer(address _to, uint _value) public payable {

        //check if sender has enough balance
        require(balanceOf[msg.sender] >= _value);

        //check value is not zero
        require(balanceOf[_to] + _value > balanceOf[_to]);

        //debit from sender
        balanceOf[msg.sender] -= _value;

        //creatit to the to address
        balanceOf[_to] += _value;

        emit addressLogger(_to);
        emit valueLogger(_value);

I've successfully compiled and migrated using Truffle.
Now, I would like to test all functions of my contract. For that I've written test case like:

pragma solidity ^0.4.17;

import "truffle/Assert.sol";
import "truffle/DeployedAddresses.sol";
import "../contracts/MyToken.sol";

contract TestMyToken {

MyToken mytoken = MyToken(DeployedAddresses.MyToken()); 

function testBalanceOf() public returns(uint){

  uint balance = mytoken.BalanceOf(this);  
  uint expected = 100000;

   Assert.equal(mytoken.BalanceOf(tx.origin), expected, "Owner should have 100000 mytoken initially");

When I run the command truffle test, it gives me an error:

Error parsing C:\Users\admin\Truffle\pet-shop-tutorial\test\TestMyToken.sol: ParsedContract.sol:13:1: ParserE ror: Expected pragma, import directive or contract/interface/library definition. function testBalanceOf() public returns(uint){ ^------^ Compilation failed. See above.

Could anyone please help me to write test cases in Solidity.

  • From my experience, writing unit tests in JavaScript vs Solidity is way easier and more flexible, and you can use code coverage tools like solidity-coverage. I would advice you to look into doing that – Andrey Jul 10 '18 at 13:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.