我如何 JUnit 测试构造函数?

use*_*730 1 java junit unit-testing

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

@Test   
public void testShipConstructor() {
    assertTrue(Submarine.length == 1);      
}
Run Code Online (Sandbox Code Playgroud)

这是该类的代码:

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", "#");
    }
}
Run Code Online (Sandbox Code Playgroud)

Mik*_*ike 6

您是否在某处实例化了 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);
Run Code Online (Sandbox Code Playgroud)