Checking Stateful Properties with ScalaCheck
Learn how to test properties on stateful components with ScalaCheck and ScalaTest.
We'll cover the following...
In this lesson, we’ll see how to test mutable or stateful components using ScalaCheck. Even if immutable components are often easier to use and understand, our applications sometimes need to use mutable components. Some components in Scala might look immutable to their users, but internally their implementation might make use of a mutable state.
With ScalaCheck we can test the behavior of a mutable component. In other words, we can see how the methods affect the state of the component over time. ScalaCheck defines a library to model commands that we can use to ensure the validity of our properties.
Modeling method invocation through commands
Modeling commands in ScalaCheck can be complex. In this lesson, we’ll test the following implementation of MutableEducative
.
package mdipirro.educative.io.effectiveunitandintegrationtestinginscala.model.v2.mutableimport mdipirro.educative.io.effectiveunitandintegrationtestinginscala.model.v2.Courseclass MutableEducative(var courses: Seq[Course]):def courseByName(courseTitle: String): Option[Course] = courses find (_.title == courseTitle)infix def `with`(newCourse: Course): Either[String, MutableEducative] =courses find (_.title.equalsIgnoreCase(newCourse.title)) matchcase Some(_) => Left(s"A course with title ${newCourse.title} already exists")case None =>courses = courses :+ newCourseRight(this)infix def without(courseTitle: String): MutableEducative =courses = courses filterNot (_.title.equalsIgnoreCase(courseTitle))this
We’ll test the interactions between the with
and without
methods. For clarity we’ll explain relevant snippets of code step by step. You’ll find the complete test suite at the end of the lesson.
Everything starts from the ...