Running on Java 19-ea+23-1706 (Preview)
Home of The JavaSpecialists' Newsletter

3.8 Testing the shuffle() method

Juppies 2 by Dr Heinz M. Kabutz

We want to make sure that our char[] shuffle method works. We take the words "hello world" and convert those to the letters as a char[] by calling the method toCharArray().

We then create our ArrayShuffler and call shuffle(letters). We obviously don't expect them to be "hello world" after we have shuffled them. We thus assert that the shuffled String is not equal to "hello world". We then sort the chars and make sure that they are equal to "dehllloorw", making sure that we have the same characters are before (remember what happened in the last session). We also check that if we shuffle them twice that we get a different order.

A good idea is to add a description into our unit test assertions to give hints to anyone working on our system to figure out precisely why the test may be failing.

Let's change the shuffle() method to always use the same sequence by creating new Random(0). Remember from session 2 that this starts the random number sequence at a predictable location. We now see that if we shuffle twice, we get the same word and thus fail the test.

Our test for the shuffle(char[]) method is actually a bit better than the test we wrote for shuffle(int[]). If we create Random with any constant value, we have a predictable shuffling. However, in shuffle(int[]) all we check is that we did not use Random(0). If we use Random(42), the test will pass, even though the words are not shuffled well at all. Homework for you will be to improve the test for shuffle(int[]) to also fail in that case.

Let us commit the changes for this session so far.


When you load these comments, you'll be connected to Disqus. Privacy Statement.

Table of Contents

We hope you enjoyed this tutorial. If you did, you will also enjoy our courses. We suggest you start with Extreme Java - Advanced Java, followed by Extreme Java - Concurrency Performance for Java 8.

About the Author

Heinz Kabutz Java Conference Speaker

Java Champion, author of the Javaspecialists Newsletter, conference speaking regular... About Heinz

Superpack '22

Superpack '22 Our entire Java Specialists Training in one huge bundle more...

Free Java Book

Dynamic Proxies in Java Book
Java Training

We deliver relevant courses, by top Java developers to produce more resourceful and efficient programmers within their organisations.

Java Consulting

We can help make your Java application run faster and trouble-shoot concurrency and performance bugs...

Java Emergency?

If your system is down, we will review it for 15 minutes and give you our findings for just 1 € without any obligation.