【发布时间】:2016-08-15 16:27:25
【问题描述】:
我目前正在学习 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;
}
【问题讨论】:
-
您的单元测试会清楚地说明失败的原因。请添加表明您的测试失败的错误消息。
-
另请注意,这是一种可怕的测试方式,没有抛出异常......只需调用构造函数,如果抛出异常,测试无论如何都会失败。如果这些是检查的异常,我会让它们不检查(你需要特定的异常吗?)如果你不能这样做,只需让测试方法声明它可以抛出它们。
-
另外,如果
rank在[0, 12]范围内,而suit在[0, 3]范围内,你为什么要使用suit % 4和rank % 13而不仅仅是suit和rank?
标签: java unit-testing