Matchers
Asserções expressivas.
Matchers é uma aula grátis de Scala for Backend Engineering & Functional Programming no CoddyKit. Esta é a aula 2 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 are Matchers?
ScalaTest matchers provide an expressive, English-like syntax for assertions. Instead of assert(x == 3), you write x shouldBe 3, producing readable tests and clear failure messages.
Mixing in Matchers
Mix the Matchers trait into your spec to unlock the DSL. It combines with any testing style.
import org.scalatest.flatspec.AnyFlatSpec
import org.scalatest.matchers.should.Matchers
class DemoSpec extends AnyFlatSpec with Matchers {
"A value" should "equal itself" in {
val x = 3
x shouldBe 3
}
}Equality Matchers
Check equality with shouldBe or should equal. Both compare with == but read naturally.
import org.scalatest.flatspec.AnyFlatSpec
import org.scalatest.matchers.should.Matchers
class EqSpec extends AnyFlatSpec with Matchers {
"sum" should "be correct" in {
(2 + 2) shouldBe 4
(2 + 2) should equal (4)
}
}Comparison Matchers
Numeric comparisons read like prose: should be >, should be <=, and ranges with be within for floating point tolerance.
import org.scalatest.flatspec.AnyFlatSpec
import org.scalatest.matchers.should.Matchers
class CmpSpec extends AnyFlatSpec with Matchers {
"a number" should "compare" in {
7 should be > 3
7 should be <= 7
2.0 shouldBe 2.0 +- 0.01
}
}String Matchers
Matchers for strings include startWith, endWith, include, and regex with fullyMatch regex.
import org.scalatest.flatspec.AnyFlatSpec
import org.scalatest.matchers.should.Matchers
class StrSpec extends AnyFlatSpec with Matchers {
"a string" should "match parts" in {
"hello world" should startWith ("hello")
"hello world" should include ("o w")
"hello world" should endWith ("world")
}
}Collection Matchers
Inspect collections fluently: have size, contain, contain allOf, and emptiness with shouldBe empty.
import org.scalatest.flatspec.AnyFlatSpec
import org.scalatest.matchers.should.Matchers
class ColSpec extends AnyFlatSpec with Matchers {
"a list" should "have expected contents" in {
List(1, 2, 3) should have size 3
List(1, 2, 3) should contain (2)
List.empty[Int] shouldBe empty
}
}Boolean and Option Matchers
Match truthiness and Option contents directly: shouldBe true, shouldBe defined, and should contain for the inner value.
import org.scalatest.flatspec.AnyFlatSpec
import org.scalatest.matchers.should.Matchers
class OptSpec extends AnyFlatSpec with Matchers {
"an option" should "be inspected" in {
Some(5) shouldBe defined
Some(5) should contain (5)
None shouldBe empty
}
}Combining Matchers
Combine expectations with and / or for compound assertions.
import org.scalatest.flatspec.AnyFlatSpec
import org.scalatest.matchers.should.Matchers
class CombineSpec extends AnyFlatSpec with Matchers {
"a number" should "satisfy both" in {
7 should (be > 0 and be < 10)
}
}Testing for Exceptions
Use an [Exception] should be thrownBy { ... } or assertThrows to verify that code fails as expected.
import org.scalatest.flatspec.AnyFlatSpec
import org.scalatest.matchers.should.Matchers
class ExSpec extends AnyFlatSpec with Matchers {
"dividing by zero" should "throw" in {
an [ArithmeticException] should be thrownBy (1 / 0)
}
}Why Matchers Help
Beyond readability, matchers produce descriptive failure messages. A failed List(1,2) should have size 3 reports the expected and actual size, unlike a bare assert that only says the boolean was false.
shouldBe vs should equal
They are nearly identical; shouldBe is terser and gives slightly cleaner messages for simple equality, while should equal supports custom Equality instances for advanced comparisons.
Quick Check
Test your knowledge of matchers.
Recap
You learned ScalaTest matchers:
- Mix in
Matchersfor the DSL. - Equality:
shouldBe,should equal; comparisons withbe >,+- tolerance. - Strings:
startWith,include; collections:have size,contain. - Exceptions:
should be thrownBy. - Matchers give clear, descriptive failures.
Perguntas Frequentes
A aula “Matchers” é grátis?
Sim — o texto completo de “Matchers” é 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 “Matchers”?
Asserções expressivas. 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 2 de 4.
Quanto tempo leva a aula “Matchers”?
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.