0Pricing
Testing Mastery: JUnit, Mockito & Integration Tests · Lección

Anotaciones básicas de JUnit 5

Explore anotaciones esenciales de JUnit 5 como @Test, @BeforeEach y @AfterEach, así como sus aplicaciones prácticas.

Anotaciones básicas de JUnit 5 es una lección gratuita de Testing Mastery: JUnit, Mockito & Integration Tests 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 Testing Mastery: JUnit, Mockito & Integration Tests, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de Testing Mastery: JUnit, Mockito & Integration Tests incluye 4 lecciones en total.

Partes de esta lección aún no han sido traducidas y se muestran en inglés.

What are JUnit Annotations?

In JUnit 5, annotations are markers that tell the runner how to run your tests — defining test methods, setup, and cleanup.

Marking Tests with @Test

The core annotation is @Test. Put it above any method and JUnit runs it as a test, reporting pass or fail.

Your First Test Method

Here’s @Test in action: a method that asserts 1 + 1 equals 2. (Assertions like assertEquals are coming up next lesson.)

package com.coddykit;

import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;

class SimpleTest {

    @Test
    void additionTest() {
        int result = 1 + 1;
        assertEquals(2, result, "1 + 1 should be 2");
    }
}

Setup Before Each Test: @BeforeEach

@BeforeEach runs before every test method, giving each one a fresh, known state — so your tests stay independent and reliable.

@BeforeEach in Practice

Here @BeforeEach resets a message before each test runs, so both tests start from the same clean state.

package com.coddykit;

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertTrue;

class BeforeEachTest {

    String message;

    @BeforeEach
    void setup() {
        message = "Hello CoddyKit!";
        System.out.println("Setup called."); // For illustration
    }

    @Test
    void testMessageStartsWithHello() {
        assertTrue(message.startsWith("Hello"));
    }

    @Test
    void testMessageLength() {
        assertTrue(message.length() > 5);
    }
}

Cleanup After Each Test: @AfterEach

@AfterEach runs after every test method — perfect for closing files, releasing connections, or resetting state so tests don’t bleed into each other.

@AfterEach in Action

Here @AfterEach tears down state after each test, clearing the log so the next test starts clean.

package com.coddykit;

import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertTrue;

class AfterEachTest {

    StringBuilder log;

    @BeforeEach
    void setup() {
        log = new StringBuilder("Test started. ");
    }

    @Test
    void testLogAppendOne() {
        log.append("Action 1. ");
        assertTrue(log.toString().contains("Action 1"));
    }

    @Test
    void testLogAppendTwo() {
        log.append("Action 2. ");
        assertTrue(log.toString().contains("Action 2"));
    }

    @AfterEach
    void teardown() {
        System.out.println("Log after test: " + log.toString());
        log = null; // Simulate cleanup
    }
}

Understanding the Test Flow

The lifecycle for each test is fixed: @BeforeEach, then the @Test method, then @AfterEach — repeating per test to guarantee isolation.

Order of Execution

Arrange the following actions in the correct order as JUnit executes them for each @Test method.

Recap: Essential JUnit Annotations

You’ve learned the essentials: @Test marks a test, @BeforeEach sets up, and @AfterEach cleans up. Assertions are up next.

Preguntas frecuentes

¿La lección «Anotaciones básicas de JUnit 5» es gratis?

Sí — el texto completo de «Anotaciones básicas de JUnit 5» 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 Testing Mastery: JUnit, Mockito & Integration Tests, actualiza a CoddyKit PRO. El curso de Testing Mastery: JUnit, Mockito & Integration Tests incluye 4 lecciones en total.

¿Qué aprenderé en «Anotaciones básicas de JUnit 5»?

Explore anotaciones esenciales de JUnit 5 como @Test, @BeforeEach y @AfterEach, así como sus aplicaciones prácticas. Practicas Testing Mastery: JUnit, Mockito & Integration Tests 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 Testing Mastery: JUnit, Mockito & Integration Tests?

No se requiere experiencia previa. Testing Mastery: JUnit, Mockito & Integration Tests 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 «Anotaciones básicas de JUnit 5»?

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 Testing Mastery: JUnit, Mockito & Integration Tests?

Sí. Cada lección de Testing Mastery: JUnit, Mockito & Integration Tests 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. Introducción a las pruebas unitarias
  2. Anotaciones básicas de JUnit 5
  3. Aserciones y ejecución en JUnit
  4. Organización de pruebas con @DisplayName y anidamiento
← Volver a Testing Mastery: JUnit, Mockito & Integration Tests