Search code examples
scalaunit-testingscalatest

How would I unit test a method that internally shuffles an array randomly


I have a method that looks like this:

def compute[T](l: List[T]): List[T] = {
    val shuffled = util.Random.shuffle(l)
    // do some more computations
}

I wanted to seed the random number generator for my unit tests so that I don't have to break down my method into two methods and test only the computation, since this is the method that will be used externally. Is this possible to do in ScalaTest?


Solution

  • I don't have much background in ScalaTest, but if you call setSeed(seed: Long): Unit then you'll always get the same shuffle for any given seed value.

    scala> util.Random.shuffle(Seq(1,2,3,4,5,6,7,8,9,0))
    res0: Seq[Int] = List(6, 0, 8, 5, 4, 7, 2, 3, 1, 9)
    
    scala> util.Random.setSeed(57L)
    
    scala> util.Random.shuffle(Seq(1,2,3,4,5,6,7,8,9,0))
    res1: Seq[Int] = List(5, 3, 2, 0, 6, 8, 7, 4, 1, 9)
    
    scala> util.Random.setSeed(57L)
    
    scala> util.Random.shuffle(Seq(1,2,3,4,5,6,7,8,9,0))
    res2: Seq[Int] = List(5, 3, 2, 0, 6, 8, 7, 4, 1, 9)