public class Player implements Comparable<Player> {
//Fields
private Name name;
private Rollable rollable;
//Constructors
public Player() {
name = new Name();
rollable = new Rollable();
}
public Player(Name name) {
this.name = name;
rollable = new Rollable();
}
public Player(Name name, Rollable rollable) {
this.name = name;
this.rollable = rollable;
}
您好,对于我放置
rollable = new Rollable();
的构造函数,我收到一条错误消息,指出它是Cannot instantiate the type rollable
。在下面,我添加了JUnit测试,还将添加Rollable类的代码
@Test
public void testDefaultConstructor() {
Player p = new Player();
assertEquals("Name field should be initialised with a default Name object ", new Name(), p.
getName());
assertTrue(“播放器的rollable字段应使用Rollable接口的实现实例初始化”,p.getRollable()Rollable实例);
}
@Test
public void testCustomConstructor1arg() {
Name n = new Name("Joe", "Bloggs");
Player p = new Player(n);
assertSame("Player's name field should be initialised with and return the same object received by the constructor", n, p.getName());
assertTrue("Player's rollable field should be initialised with an implementing instance of the Rollable interface", p.getRollable() instanceof Rollable);
}
现在下面是默认构造函数的JUnit测试,这也给我
Players rollable field should be initialised with an implementing instance of the Rollable interface
带来了失败,但是,我所有其他的JUnit测试都通过了。 @Test
public void testDefaultConstructor() {
Player p = new Player();
assertEquals("Name field should be initialised with a default Name object ", new Name(), p.getName());
assertTrue("Player's rollable field should be initialised with an implementing instance of the Rollable interface", p.getRollable() instanceof Rollable);
}
我的Rollable类的代码如下:
public interface Rollable {
public void roll();
public int getScore();
}
我的可滚动代码的方法如下:
//Methods
public Name getName() {
return name;
}
public void setName(Name name) {
this.name = name;
}
public Rollable getRollable() {
return rollable;
}
public void rollDice() {
rollable.roll();
}
public int getDiceScore() {
return rollable.getScore();
}
感谢我为失败而苦苦挣扎的所有帮助。
最佳答案
您的getRollable()
方法是:
public Rollable getRollable() {
return rollable;
}
因此,例如,如果从构造函数调用它,则:
public Player() {
name = new Name();
rollable = getRollable();
}
然后将为
rollable
分配rollable
的值,默认情况下为null
。这样,当您在测试中再次调用
getRollable()
时,您将获得分配给该字段的值-null
-并且根据定义-null instanceof Rollable
为false。相反,您需要创建一个新的
Rollable
实例,例如:rollable = new Rollable();
(不知道它是否可以直接实例化。您没有提供
Rollable
类的声明)。