Java – JUnit test method with random nature
I am working for myself on a small project and I am using it as an opportunity to understand unit testing and maintain correct documentation
I have a deck course that represents a card (it's very simple. To be honest, I can be sure it doesn't have unit tests, but like I said I'm used to unit tests), it has a shuffle () method to change the order of cards on the deck
The implementation is very simple and will work:
public void shuffle() { Collections.shuffle(this.cards); }
However, how to implement unit testing of this method My first idea is to check that after calling shuffle (), the top card on the deck is different, but of course it may be the same My second idea is to check whether the order of the whole card has changed, but they may also be the same So, how can I write a test to ensure that this method works in all cases? And, in general, how do you unit test results depends on some random methods?
Cheers!
Pete
Solution
It is very difficult, if not impossible, to assert whether your shuffle method actually shuffles The default random number generator is somewhat random It is impossible to test whether you are satisfied with this random sex appeal, because it takes too much time What you're actually testing is that the random number generator itself doesn't make any sense
What can be tested is the invariants of this method
>If you exit this method, there should be exactly the same number of cards on the deck as you entered. > Shuffling methods should not introduce duplication
You can of course create a test to check that there are no duplicate deck returns in the order of N shuffles But for some time, the test may fail (but it is unlikely, as has been said in other answers)
The other thing to consider is the random number generator itself If this is just a toy project, Java util. Random is enough If you plan to create some online card games, consider using Java security. SecureRandom.