0Pricing
Scala for Backend Engineering & Functional Programming · Lección

Matchers

Aserciones expresivas

Matchers es una lección gratuita de Scala for Backend Engineering & Functional Programming en CoddyKit. Esta es la lección 2 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de Scala for Backend Engineering & Functional Programming, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de Scala for Backend Engineering & Functional Programming incluye 4 lecciones en total.

Partes de esta lección aún no han sido traducidas y se muestran en 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 Matchers for the DSL.
  • Equality: shouldBe, should equal; comparisons with be >, +- tolerance.
  • Strings: startWith, include; collections: have size, contain.
  • Exceptions: should be thrownBy.
  • Matchers give clear, descriptive failures.

Preguntas frecuentes

¿La lección «Matchers» es gratis?

Sí — el texto completo de «Matchers» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de Scala for Backend Engineering & Functional Programming, actualiza a CoddyKit PRO. El curso de Scala for Backend Engineering & Functional Programming incluye 4 lecciones en total.

¿Qué aprenderé en «Matchers»?

Aserciones expresivas Practicas Scala for Backend Engineering & Functional Programming con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.

¿Necesito experiencia previa para empezar Scala for Backend Engineering & Functional Programming?

No se requiere experiencia previa. Scala for Backend Engineering & Functional Programming en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 2 de 4.

¿Cuánto tiempo toma la lección «Matchers»?

La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.

¿Puedo escribir y ejecutar código en esta lección de Scala for Backend Engineering & Functional Programming?

Sí. Cada lección de Scala for Backend Engineering & Functional Programming incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.

Todas las lecciones de este curso

  1. Estilos de ScalaTest
  2. Matchers
  3. Pruebas basadas en propiedades
  4. Mocking y fixtures
← Volver a Scala for Backend Engineering & Functional Programming