Skip to content
Advertisement

Unit testing of a shuffle method on a list

Consider the following class:

JavaScript

How would I unit test the shuffle() method? I am using JUnit 4 for testing.

I have the following options:

  1. Test shuffle() to see that it does not generate an exception.
  2. Test shuffle() and check if the deck actually gets shuffled.

Example pseudocode of option 2:

JavaScript

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?

Advertisement

Answer

Currently, your class is tightly coupled with the Collections.shuffle function. Static functions are notorious for making things more difficult to test. (On top of that, there’s no point in you testing Collections.shuffle; presumably, it works correctly.)

In order to address this, you can introduce a seam in your class for this shuffling functionality. This is done by extracting the shuffle function into a role (represented by an interface). For example:

JavaScript

Then, your Deck class can be configured to keep a reference to an instance of some implementation of this interface, and invoke it when necessary:

JavaScript

This allows your unit test to use a test double, like a mock object, to verify that the expected behavior occurs (i.e., that shuffle invokes shuffle on the provided ICardShuffler).

Finally, you can move the current functionality into an implementation of this interface:

JavaScript

Note: In addition to facilitating testing, this seam also allows you to implement new methods of shuffling without having to modify any of the code in Deck.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement