我目前在学习Java。我进行了抛出异常的单元测试。我跑了单元测试但失败了。任何承担这一点?为什么Java在Java中的单元测试失败?
这是我的代码单元测试的
public Card(int rank, int suit) throws SuitOutOfRangeException, RankOutOfRangeException {
// TODO: Re-write this Constructor to throw exceptions
try {
if (suit > 4 || suit < 0) {
throw new SuitOutOfRangeException();
}
this.suit = suit % 4;
} catch (SuitOutOfRangeException ex) {
System.out.println("Your input value for suit is out of the specified range");
}
try {
if (rank > 12 || rank < 0) {
throw new RankOutOfRangeException();
}
this.rank = rank % 13;
} catch (RankOutOfRangeException ex) {
System.out.println("Your input value for rank is out of the specified range");
}
}
部分是如下所示:
@Test
public void testConstructorShouldThrowRankOutOfRangeException() {
boolean expected = true;
boolean actual = false;
try {
Card c = new Card(100,1);
actual = false;
} catch (SuitOutOfRangeException ex) {
actual = false;
} catch (RankOutOfRangeException ex) {
actual = true;
}
assertEquals(expected,actual);
}
的解决方案是本
public Card(int rank, int suit) throws SuitOutOfRangeException, RankOutOfRangeException {
if (rank <0 || rank > 12) throw new RankOutOfRangeException();
if (suit <0 || suit >3) throw new SuitOutOfRangeException();
this.suit = suit % 4;
this.rank = rank % 13;
}
你的单元测试会说清楚失败的原因。请添加显示您的测试失败的错误消息。 – randominstanceOfLivingThing
还要注意,这是一种可怕的测试方法,不会引发任何异常......只是调用构造函数,并且如果引发异常,测试将无法继续。如果这些是检查异常,我会让它们不被检查(你是否需要特定的异常?),如果你不能这样做,只要让测试方法声明它可以抛出它们。 –
此外,如果'rank'在范围内[[0,12]'和'suit'在范围内[[0,3]],为什么你使用'suit%4'和'rank%13'只是'西装'和'等级'? –