我如何JUnit测试构造函数?

时间:2013-03-30 12:54:41

标签: java unit-testing junit

此测试运行但失败。不知道为什么?有一个长度为1的潜水艇。

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

以下是该类的代码:

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", "#");
    }
}

2 个答案:

答案 0 :(得分:4)

您是否在某处实例化了Ship类?我假设构造函数采用值n来表示长度?

假设public class Submarine extends Ship

以及Submarine(int size){}Ship(int ship){}

的构造函数

您的测试应包括:

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

答案 1 :(得分:1)

Submarine是班级名字吗?在这种情况下,我认为长度是静态的,因为您以静态方式访问它。所以你应该在构造函数之外初始化长度。此外,您的测试不会测试构造函数。

相关问题