I am currently learning Java. I carried out unit testing for throwing exceptions. I ran the the unit test but failed. Any take on this?
This is my code
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");
}
}
Part of the unit test is as the following:
@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);
}
The solution is this
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;
}