2013-03-30 77 views
1

此测试运行但失败。不知道为什么?有与长度级潜艇1如何JUnit测试构造函数?

@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

什么是'潜水艇'?你能展示这堂课吗? –

+2

测试对象的行为,而不是它是否构造或其值。 – yehe

+0

public abstract class Ship { \t \t private int size; \t \t \t public static int length; \t \t 保护\t船(INT大小,字符串型,字符串简短版本){ \t \t \t this.size =大小; \t \t \t this.setType(type); \t \t \t this.shortForm = shortForm; \t \t} \t \t \t \t公共静态无效setLength(INT长度){ \t \t} \t \t 公共\t INT的getLength(){ \t \t \t返回长度; \t \t} \t \t \t INT \t的getSize(){ \t \t \t返回大小; \t \t} \t} \t --------- \t \t 公共类海底延伸船舶{ \t \t私人最终静态INT SIZE = 1; \t \t/** \t \t *构造函数,设置继承的长度变量。 \t \t */ \t \t公共潜艇(){ \t \t \t超级(SIZE “海底”, “#”); \t \t} \t} – user742730

回答

4

你实例化你的船级地方?我假设构造函数的值为n来表示长度?

假设public class Submarine extends Ship

和任Submarine(int size){}Ship(int ship){}构造

您的测试应包括:

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

我在一个阵列车队中实例化了新的潜艇。现在测试不正确地在assertEquals(submarine.getLenth(),0)中传递0,@Test \t public void testShipConstructor2(){ \t \t Ship [] fleet = new Ship [10]; \t \t int length = 1; \t \t舰队[3] =新潜艇(); \t \t assertEquals(Submarine.getLength(),0); \t \t} – user742730

+1

因为测试正在查看名为Length的int字段,但您的构造函数正在设置名为Size的字段。我已根据您添加的代码更新了我的代码示例... – Mike

+0

不客气。请接受解决您的问题的答案,向社区表示感谢。 – Mike

1

是潜艇的类名?在那种情况下,我认为长度是静态的,因为你以静态方式访问它。所以你应该在构造函数之外初始化长度。此外,你的测试不测试构造函数。

+0

谢谢。现在它似乎与尺寸而不是长度一起工作。\t Ship []舰队=新船[10]; \t \t int size = 1; \t \t舰队[3] =新潜艇(); \t \t assertEquals(Submarine.getSize(),1); \t \t} – user742730

+0

等一下,让静态值所做的测试工作,但停止了计划工作。所以已经恢复到不是静态值,但现在测试不起作用。是否有另一种简单的方法来测试构造函数? – user742730

+0

我不明白你的测试。在你的代码中,你永远不会初始化长度,那么为什么长度应该是1呢? – user2226834