0
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
contract voting{

address private onlyowner;
uint private Virat =0;
uint private Rohit =0;

constructor(){
        onlyowner = msg.sender;
}

function topic(string memory _c) public pure returns(string memory){
          string  memory C = _c;
           return C;
}

 function vote(uint vor)public{
     require(vor <2 , "invalid input");

     if (vor == 0){
         Virat++;
     }
     else if(vor ==1){
         Rohit++;
     }
 }
 function result() public view returns(string memory){
     if(Virat > Rohit){
         return "VIRAT";
     }
     else if(Rohit > Virat){
         return "ROHIT";
     }
     return "DRAW";
 }
}
2
  • You are using truffle in general?( To migrate/deployment/development etc?)
    – Sky
    May 21 at 22:50
  • Yeah i am using truffle for testing
    – Wiswa
    May 22 at 6:44

1 Answer 1

0
    const Voting = artifacts.require("Voting");
    contract("voting", async() =>{
    beforeEach(async() =>{
        this.voting = await Voting.new();
    });

    it("should return VIRAT", async()=>{
        await this.voting.vote(0);
        const winner = await this.voting.result();
        assert.equal(winner, "VIRAT");
    });

    it("should return ROHIT", async()=>{
        await this.voting.vote(1);
        const winner = await this.voting.result();
        assert.equal(winner, "ROHIT");
    });

    it("should return DRAW", async()=>{
        await this.voting.vote(1);
        await this.voting.vote(0);
        const winner = await this.voting.result();
        assert.equal(winner, "DRAW");
    });
});

you should keep track of addresses that have already voted to prevent the same address from voting multiple times

once you made that modification to your smart contract you cant test it usind:

  await this.voting.vote(1, {from: accounts[0]});

as you can see it is specifying the address of the account who is voting

The require validation should be tested too

you can use truffle-assertions, so install it using:

npm i truffle-assertions

and then include it in your test file:

const truffleAssertions = require("truffle-assertions");

 it("should fail when value is not 0 or 1", async ()=>{
    await truffleAssertions.reverts(this.voting.vote(2), "invalid input");
});

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.