Estilos de Pruebas
Esta página fue traducida por PageTurner AI (beta). No está respaldada oficialmente por el proyecto. ¿Encontraste un error? Reportar problema →
Kotest ofrece 10 estilos diferentes de organización de pruebas. Algunos están inspirados en otros frameworks populares para que te sientas como en casa. Otros fueron creados específicamente para Kotest.
Para usar Kotest, crea un archivo de clase que extienda uno de los estilos de prueba. Luego, dentro de un bloque init { },
define tus casos de prueba. La siguiente tabla muestra los estilos disponibles junto con ejemplos.
No hay diferencias funcionales entre los estilos. Todos permiten los mismos tipos de configuración — hilos, tags, etc. — es simplemente cuestión de preferencia cómo estructuras tus pruebas.
| Test Style | Inspired By |
|---|---|
| Fun Spec | ScalaTest |
| Describe Spec | Javascript frameworks and RSpec |
| Should Spec | A Kotest original |
| String Spec | A Kotest original |
| Behavior Spec | BDD frameworks |
| Free Spec | ScalaTest |
| Word Spec | ScalaTest |
| Feature Spec | Cucumber |
| Expect Spec | A Kotest original |
| Annotation Spec | JUnit |
Algunos equipos prefieren usar un único estilo, otros combinan varios. No hay una forma correcta o incorrecta: haz lo que mejor funcione para tu equipo.
Fun Spec
FunSpec te permite crear pruebas invocando una función llamada test con un argumento de cadena para describir la prueba,
y luego la prueba en sí como una lambda. Si tienes dudas, este es el estilo recomendado.
class MyTests : FunSpec({
test("String length should return the length of the string") {
"sammy".length shouldBe 5
"".length shouldBe 0
}
})
Las pruebas se pueden deshabilitar usando las variantes xcontext y xtest (además de las formas habituales)
class MyTests : FunSpec({
context("this outer block is enabled") {
xtest("this test is disabled") {
// test here
}
}
xcontext("this block is disabled") {
test("disabled by inheritance from the parent") {
// test here
}
}
})
String Spec
StringSpec reduce la sintaxis al mínimo absoluto.
Simplemente escribe una cadena seguida de una expresión lambda con tu código de prueba.
class MyTests : StringSpec({
"strings.length should return size of string" {
"hello".length shouldBe 5
}
})
Añadiendo configuración a la prueba.
class MyTests : StringSpec({
"strings.length should return size of string".config(enabled = false, invocations = 3) {
"hello".length shouldBe 5
}
})
Should Spec
ShouldSpec es similar a fun spec, pero usa la palabra clave should en lugar de test.
class MyTests : ShouldSpec({
should("return the length of the string") {
"sammy".length shouldBe 5
"".length shouldBe 0
}
})
Las pruebas también se pueden anidar en uno o más bloques de contexto:
class MyTests : ShouldSpec({
context("String.length") {
should("return the length of the string") {
"sammy".length shouldBe 5
"".length shouldBe 0
}
}
})
Las pruebas se pueden deshabilitar usando las variantes xcontext y xshould (además de las formas habituales)
class MyTests : ShouldSpec({
context("this outer block is enabled") {
xshould("this test is disabled") {
// test here
}
}
xcontext("this block is disabled") {
should("disabled by inheritance from the parent") {
// test here
}
}
})
Describe Spec
DescribeSpec ofrece un estilo familiar para quienes vienen de Ruby o Javascript, ya que usa
las palabras clave describe / it. Las pruebas deben anidarse en uno o más bloques describe.
class MyTests : DescribeSpec({
describe("score") {
it("start as zero") {
// test here
}
describe("with a strike") {
it("adds ten") {
// test here
}
it("carries strike to the next frame") {
// test here
}
}
describe("for the opposite team") {
it("Should negate one score") {
// test here
}
}
}
})
Las pruebas se pueden deshabilitar usando las variantes xdescribe y xit (además de las formas habituales)
class MyTests : DescribeSpec({
describe("this outer block is enabled") {
xit("this test is disabled") {
// test here
}
}
xdescribe("this block is disabled") {
it("disabled by inheritance from the parent") {
// test here
}
}
})
Behavior Spec
Popular entre quienes prefieren escribir pruebas en estilo BDD, BehaviorSpec permite usar context, given, when, then.
class MyTests : BehaviorSpec({
context("a broomstick should be able to be fly and come back on it's own") {
given("a broomstick") {
`when`("I sit on it") {
then("I should be able to fly") {
// test code
}
}
`when`("I throw it away") {
then("it should come back") {
// test code
}
}
}
}
})
Como when es una palabra reservada en Kotlin, debemos encerrarla entre backticks. Alternativamente, existen versiones con mayúsculas si prefieres evitar los backticks, ej. Context, Given, When, Then.
También puedes usar la palabra clave And en Given y When para añadir profundidad adicional:
class MyTests : BehaviorSpec({
given("a broomstick") {
and("a witch") {
`when`("The witch sits on it") {
and("she laughs hysterically") {
then("She should be able to fly") {
// test code
}
}
}
}
}
})
Nota: El ámbito Then no tiene soporte para and debido a un bug de Gradle. Para más información, ver #594
Las pruebas pueden desactivarse usando las variantes xcontext, xgiven, xwhen y xthen (además de las formas habituales)
class MyTests : BehaviorSpec({
xgiven("this is disabled") {
When("disabled by inheritance from the parent") {
then("disabled by inheritance from its grandparent") {
// disabled test
}
}
}
given("this is active") {
When("this is active too") {
xthen("this is disabled") {
// disabled test
}
}
}
})
Word Spec
WordSpec usa la palabra clave should para anidar pruebas después de una cadena de contexto.
class MyTests : WordSpec({
"String.length" should {
"return the length of the string" {
"sammy".length shouldBe 5
"".length shouldBe 0
}
}
})
También soporta la palabra clave When para añadir otro nivel de anidamiento. Nota: como when es
una palabra reservada en Kotlin, debemos usar backticks o la variante en mayúsculas.
class MyTests : WordSpec({
"Hello" When {
"asked for length" should {
"return 5" {
"Hello".length shouldBe 5
}
}
"appended to Bob" should {
"return Hello Bob" {
"Hello " + "Bob" shouldBe "Hello Bob"
}
}
}
})
Free Spec
FreeSpec permite anidar niveles arbitrarios de profundidad usando - (guión) para pruebas externas, y solo el nombre para la prueba final:
class MyTests : FreeSpec({
"String.length" - {
"should return the length of the string" {
"sammy".length shouldBe 5
"".length shouldBe 0
}
}
"containers can be nested as deep as you want" - {
"and so we nest another container" - {
"yet another container" - {
"finally a real test" {
1 + 1 shouldBe 2
}
}
}
}
})
La prueba más interna NO debe usar - (guión) después del nombre.
Feature Spec
FeatureSpec te permite usar feature y scenario, lo que resultará familiar a quienes hayan usado cucumber. Aunque no pretende ser idéntico a cucumber, las palabras clave imitan su estilo.
class MyTests : FeatureSpec({
feature("the can of coke") {
scenario("should be fizzy when I shake it") {
// test here
}
scenario("and should be tasty") {
// test here
}
}
})
Se pueden desactivar pruebas usando las variantes xfeature y xscenario (además de las formas habituales)
class MyTests : FeatureSpec({
feature("this outer block is enabled") {
xscenario("this test is disabled") {
// test here
}
}
xfeature("this block is disabled") {
scenario("disabled by inheritance from the parent") {
// test here
}
}
})
Expect Spec
ExpectSpec es similar a FunSpec y ShouldSpec pero utiliza la palabra clave expect.
class MyTests : ExpectSpec({
expect("my test") {
// test here
}
})
Las pruebas también se pueden anidar en uno o más bloques de contexto:
class MyTests : ExpectSpec({
context("a calculator") {
expect("simple addition") {
// test here
}
expect("integer overflow") {
// test here
}
}
})
Se pueden desactivar pruebas usando las variantes xcontext y xexpect (además de las formas habituales)
class MyTests : ExpectSpec({
context("this outer block is enabled") {
xexpect("this test is disabled") {
// test here
}
}
xcontext("this block is disabled") {
expect("disabled by inheritance from the parent") {
// test here
}
}
})
Annotation Spec
Si estás migrando desde JUnit, AnnotationSpec es una especificación que utiliza anotaciones como JUnit 4/5. Simplemente añade la anotación @Test a cualquier función definida en la clase de especificación.
También puedes añadir anotaciones para ejecutar acciones antes/después de pruebas/especificaciones, similar a JUnit
@BeforeAll / @BeforeClass
@BeforeEach / @Before
@AfterAll / @AfterClass
@AfterEach / @After
Si quieres ignorar una prueba, usa @Ignore.
Aunque esta especificación no ofrece grandes ventajas sobre JUnit, permite migrar pruebas existentes con relativa facilidad, ya que normalmente solo necesitas ajustar las importaciones.
class AnnotationSpecExample : AnnotationSpec() {
@BeforeEach
fun beforeTest() {
println("Before each test")
}
@Test
fun test1() {
1 shouldBe 1
}
@Test
fun test2() {
3 shouldBe 3
}
}