JUnit Test method with randomized nature
Posted
by Peter
on Stack Overflow
See other posts from Stack Overflow
or by Peter
Published on 2010-05-30T12:57:40Z
Indexed on
2010/05/30
13:02 UTC
Read the original article
Hit count: 296
Hey,
I'm working on a small project for myself at the moment and I'm using it as an opportunity to get acquainted with unit testing and maintaining proper documentation.
I have a Deck
class with represents a deck of cards (it's very simple and, to be honest, I can be sure that it works without a unit test, but like I said I'm getting used to using unit tests) and it has a shuffle()
method which changes the order of the cards in the deck.
The implementation is very simple and will certainly work:
public void shuffle()
{
Collections.shuffle(this.cards);
}
But, how could I implement a unit test for this method. My first thought was to check if the top card of the deck was different after calling shuffle()
but there is of course the possibility that it would be the same. My second thought was to check if the entire order of cards has changed, but again they could possibly be in the same order. So, how could I write a test that ensures this method works in all cases? And, in general, how can you unit test methods for which the outcome depends on some randomness?
Cheers,
Pete
© Stack Overflow or respective owner