java 我如何 JUnit 测试构造函数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15718746/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I JUnit test a constructor?
提问by user742730
This test runs but fails. Not sure why? There is a class Submarine with length 1.
此测试运行但失败。不知道为什么?有一个长度为 1 的 Submarine 类。
@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", "#");
}
}
回答by Mike
Did you instantiate your Ship class somewhere? I'm assuming the constructor takes a value n to represent the length?
您是否在某处实例化了 Ship 类?我假设构造函数采用值 n 来表示长度?
assuming public class Submarine extends Ship
假设 public class Submarine extends Ship
and a constructor of either Submarine(int size){}
or Ship(int ship){}
和一个Submarine(int size){}
或的构造函数Ship(int ship){}
your test should include:
您的测试应包括:
int desiredSize = 1;
Submarine mySub = new Submarine(desiredSize);
assertEquals(mySub.getSize(), desiredSize);
回答by user2226834
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.
潜艇是类名吗?在那种情况下,我认为 length 是静态的,因为您以静态方式访问它。所以你应该在构造函数之外初始化长度。此外,您的测试不会测试构造函数。