简体   繁体   中英

How do I JUnit test a constructor?

This test runs but fails. Not sure why? There is a class Submarine with length 1.

@Test   
public void testShipConstructor() {
    assertTrue(Submarine.length == 1);      
}

Here is the code for the class:

public abstract class Ship {

    private int size;
    public static int length;

    protected Ship(int size, String type, String shortForm) {
        this.size = size;
        this.setType(type);
        this.shortForm = shortForm;
    }

    public static void setLength(int length) {
    }

    public int getLength() {
        return length;
    }

    int getSize() {
        return size;
    }
}

public class Submarine extends Ship {

    private final static int SIZE = 1;

    /**
     * * Constructor, sets inherited length variable.
     */
    public Submarine() {
        super(SIZE, "Submarine", "#");
    }
}

Did you instantiate your Ship class somewhere? I'm assuming the constructor takes a value n to represent the length?

assuming public class Submarine extends Ship

and a constructor of either Submarine(int size){} or Ship(int ship){}

your test should include:

int desiredSize = 1;
Submarine mySub = new Submarine(desiredSize);
assertEquals(mySub.getSize(), desiredSize);

Is Submarine the class-name? In that case I think length is static, because you access it in a static way. So you should initialize length outside the constructor. Furthermore then your test does not test the constructor.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM