0

Say I have a contract:

contract Reverts{
    constructor(param1){
        require(param1);
    }
}

If param1 is false, the constructor should fail and revert state.

truffle-assertions allows me to check if an existing contract abstraction's function will revert using await truffleAssertions.reverts(Reverts.someFunc());

That doesn't apply to constructors, since they are what make the contract abstraction in the first place.

How can I achieve this functionality with a constructor, instead of a regular function?

In a Truffle JavaScript testing file:

const truffleAssertions = require("truffle-assertions");
const Reverts = artifacts.require("Reverts");
let reverts;

contract("Reverts", (accounts) => {
    it("Check that param1=false, constructor reverts.", async () =>{
        // What to do here?
    });
});
1
  • 1
    Use a try/catch block
    – Julissa DC
    Jun 23, 2022 at 19:21

2 Answers 2

0

For this example contract, I used:

contract("Reverts", (accounts) => {
    it("Check that param1=false, constructor reverts.", async () =>{
        try{
            await Reverts.new(false);
        }
        catch{return;}
        assert.fail("Constructor does not revert when param1=false.");
    });
});

If the constructor reverts, the test simply returns and shows as passing. If it does not revert, then the assert statement is reached, causing an fail.

0

With @openzeppelin/test-helpers you can do:

const { expectRevert } = require("@openzeppelin/test-helpers");
const Reverts = artifacts.require("Reverts");

contract("Reverts", (accounts) => {
    it("Check that param1=false, constructor reverts.", async () =>{
        await expectRevert.unspecified(Reverts.new(false));
    });
});

or

await expectRevert(Reverts.new(false), "some revert string");

if the require include a reason string.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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