Testes baseados em propriedades
ScalaCheck.
Testes baseados em propriedades é uma aula grátis de Scala for Backend Engineering & Functional Programming no CoddyKit. Esta é a aula 3 de 4. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de Scala for Backend Engineering & Functional Programming, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de Scala for Backend Engineering & Functional Programming inclui 4 aulas no total.
Partes desta aula ainda não foram traduzidas e aparecem em inglês.
What is Property-Based Testing?
In property-based testing you state a general property that should hold for all inputs, and the framework generates many random inputs to try to falsify it. This finds edge cases hand-written examples miss.
Example vs Property
An example test checks one case: reverse(List(1,2,3)) == List(3,2,1). A property states a rule: reversing twice yields the original list, for any list. The framework checks that rule on hundreds of generated lists.
ScalaCheck
ScalaCheck is the property-testing library for Scala. Add it as a test dependency; it integrates with ScalaTest.
libraryDependencies += "org.scalatestplus" %% "scalacheck-1-17" % "3.2.18.0" % TestforAll
The core construct is forAll: it generates random values and asserts the property body for each. Here we test that addition is commutative.
import org.scalatest.flatspec.AnyFlatSpec
import org.scalatest.matchers.should.Matchers
import org.scalatestplus.scalacheck.ScalaCheckPropertyChecks
class AddSpec extends AnyFlatSpec with Matchers with ScalaCheckPropertyChecks {
"addition" should "be commutative" in {
forAll { (a: Int, b: Int) =>
a + b shouldBe b + a
}
}
}A Round-Trip Property
A powerful pattern is the round trip: encoding then decoding (or reversing twice) should return the original value, for any input.
import org.scalatest.flatspec.AnyFlatSpec
import org.scalatest.matchers.should.Matchers
import org.scalatestplus.scalacheck.ScalaCheckPropertyChecks
class RevSpec extends AnyFlatSpec with Matchers with ScalaCheckPropertyChecks {
"reverse" should "be its own inverse" in {
forAll { (xs: List[Int]) =>
xs.reverse.reverse shouldBe xs
}
}
}Generators
ScalaCheck supplies Gen generators for built-in types automatically. You can also build custom ones, e.g. Gen.choose(1, 100) for a bounded integer.
import org.scalacheck.Gen
val smallInt: Gen[Int] = Gen.choose(1, 100)
val nonEmpty: Gen[List[Int]] = Gen.nonEmptyListOf(Gen.choose(0, 9))Using a Custom Generator
Pass a generator to forAll to constrain the inputs, for example only positive numbers.
import org.scalatest.flatspec.AnyFlatSpec
import org.scalatest.matchers.should.Matchers
import org.scalatestplus.scalacheck.ScalaCheckPropertyChecks
import org.scalacheck.Gen
class PosSpec extends AnyFlatSpec with Matchers with ScalaCheckPropertyChecks {
"abs" should "stay positive" in {
forAll(Gen.choose(1, 1000)) { (n: Int) =>
math.abs(n) should be > 0
}
}
}Shrinking
When a property fails, ScalaCheck shrinks the failing input to the smallest example that still fails. Instead of a huge random list, you get a minimal counterexample that is easy to debug.
Conditional Properties
Use whenever to restrict a property to inputs that satisfy a precondition. Inputs that fail the condition are discarded.
import org.scalatest.flatspec.AnyFlatSpec
import org.scalatest.matchers.should.Matchers
import org.scalatestplus.scalacheck.ScalaCheckPropertyChecks
class DivSpec extends AnyFlatSpec with Matchers with ScalaCheckPropertyChecks {
"division" should "hold for nonzero divisors" in {
forAll { (a: Int, b: Int) =>
whenever(b != 0) {
(a / b) * b + (a % b) shouldBe a
}
}
}
}Good Properties to Test
Useful property categories:
- Round trips: encode/decode, reverse/reverse.
- Invariants: sorting preserves length.
- Algebraic laws: commutativity, associativity, identity.
When to Use It
Property testing complements example tests; it does not replace them. Use it for pure functions with clear mathematical or structural rules. Keep targeted example tests for specific known cases and regressions.
Quick Check
Test your knowledge of property-based testing.
Recap
You learned property-based testing with ScalaCheck:
- State properties true for all inputs; the framework generates many.
forAlldrives generation;Gencreates custom inputs.wheneveradds preconditions; failures are shrunk to minimal examples.- Great for round trips, invariants, and algebraic laws.
Perguntas Frequentes
A aula “Testes baseados em propriedades” é grátis?
Sim — o texto completo de “Testes baseados em propriedades” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de Scala for Backend Engineering & Functional Programming, atualize para CoddyKit PRO. O curso de Scala for Backend Engineering & Functional Programming inclui 4 aulas no total.
O que vou aprender em “Testes baseados em propriedades”?
ScalaCheck. Você pratica Scala for Backend Engineering & Functional Programming com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.
Preciso ter experiência prévia para começar Scala for Backend Engineering & Functional Programming?
Nenhuma experiência prévia é necessária. Scala for Backend Engineering & Functional Programming no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 3 de 4.
Quanto tempo leva a aula “Testes baseados em propriedades”?
A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.
Posso escrever e executar código nesta aula de Scala for Backend Engineering & Functional Programming?
Sim. Cada aula de Scala for Backend Engineering & Functional Programming inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.
Todas as aulas deste curso
- Estilos do ScalaTest
- Matchers
- Testes baseados em propriedades
- Mocks e fixtures