Consider the following class:
public class Deck {
private final Queue<Card> queue = new LinkedList<>();
public Deck() { }
public Deck(final Collection<Card> cards) {
Objects.requireNonNull(cards);
queue.addAll(cards);
}
public void add(final Card card) {
Objects.requireNonNull(card);
queue.add(card);
}
public void addAll(final Collection<Card> cards) {
Objects.requireNonNull(cards);
queue.addAll(cards);
}
public void shuffle() {
Collections.shuffle((List<Card>)queue);
}
public Card take() {
return queue.remove();
}
}
How would I unit test the shuffle()
method? I am using JUnit 4 for testing.
I have the following options:
- Test
shuffle()
to see that it does not generate an exception. - Test
shuffle()
and check if the deck actually gets shuffled.
Example pseudocode of option 2:
while notShuffled
create new Deck
take cards and check if they are shuffled
The only culprit here is that when executing a test written for option 2 (which also inheritly includes option 1), if the shuffling does not work as intended, then the code execution will never stop.
How would I solve this issue? Is it possibly to limit the execution time in JUnit tests?