Question

I am trying use assertions on a constructor in a abstract class, the String variable thename cannot be null or empty and the int variable thesize cannot be negative or zero here is how I tried to do it but the test case I was provided does not pass. How would I assert the conditions for the constructor?

public abstract class AbstractItem implements Item{

    private int size;
    private String name;

    public AbstractItem(String thename, int thesize){
        assert thename != null;
        assert thename.length() > 0;
        assert thesize > 0;
        name = thename;
        size = thesize;
    } 

    public final int getSize(){
        return size;
    }
    public String toString(){
        return name;
    }
}
Was it helpful?

Solution

Enabling and Disabling Assertions

By default, assertions are disabled at runtime. Two command-line switches allow you to selectively enable or disable assertions.

To enable assertions at various granularities, use the -enableassertions, or -ea, switch. To disable assertions at various granularities, use the -disableassertions, or -da, switch. You specify the granularity with the arguments that you provide to the switch:

OTHER TIPS

If you use Spring, you could also use their Assert, it comes with handy error messages too, so you can have a humanly readable error for why an assertion failed. Here is a snippet from Spring's ACL library, if sid is null, you'll get a nice error message saying so.

public Long createOrRetrieveSidPrimaryKey(Sid sid, boolean allowCreate) {
    Assert.notNull(sid, "Sid required");
    // more code here ....
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top