我目前在學習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'只是'西裝'和'等級'? –