Ir al contenido principal
Versión: 6.2 🚧

Estilos de Pruebas

[Traducción Beta No Oficial]

Esta página fue traducida por PageTurner AI (beta). No está respaldada oficialmente por el proyecto. ¿Encontraste un error? Reportar problema →

Kotest ofrece 8 estilos diferentes para definir pruebas. Algunos están inspirados en otros frameworks de pruebas 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 StyleInspired By
Fun SpecScalaTest
Describe SpecJavascript frameworks and RSpec
Should SpecA Kotest original
Behavior SpecBDD frameworks
Free SpecScalaTest
Word SpecScalaTest
Feature SpecCucumber
Expect SpecA Kotest original
consejo

Algunos equipos prefieren exigir el uso de un único estilo, otros prefieren mezclar y combinar. No hay una forma correcta o incorrecta: haz lo que mejor le parezca a 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
}
}
})

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 palabras clave describe / it. Las pruebas deben anidarse en uno o más bloques describe. context también puede usarse como alias de 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
}
}

context("big scorers") {
describe("for the opposite team") {
it("Should negate one score") {
// test here
}
}
}
}
})

Las pruebas pueden deshabilitarse usando las variantes xcontext, 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
}
}
xcontext("this block is also 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
}
}
}
}
})
nota

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
}
}
}
}
})
precaución

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
}
}
})