Zum Inhalt

_

_

_

JUnit Comprehensive Cheatsheet

• Installation

Platform Installation Method
Maven (JUnit 5) Add to INLINE_CODE_8: INLINE_CODE_9
Maven (JUnit 4) Add to INLINE_CODE_10: INLINE_CODE_11
Gradle (JUnit 5) Add to INLINE_CODE_12: INLINE_CODE_13 and INLINE_CODE_14
Gradle (JUnit 4) Add to INLINE_CODE_15: INLINE_CODE_16
Ubuntu/Debian INLINE_CODE_17 (includes JUnit support)
macOS INLINE_CODE_18 or INLINE_CODE_19
Windows (Chocolatey) INLINE_CODE_20 or INLINE_CODE_21
Standalone JAR INLINE_CODE_22
_
(JUnit 5)
Annotation Description
INLINE_CODE_23 Marks a method as a test method
INLINE_CODE_24 Executes before each test method in the class
INLINE_CODE_25 Executes after each test method in the class
INLINE_CODE_26 Executes once before all tests (must be static)
INLINE_CODE_27 Executes once after all tests (must be static)
INLINE_CODE_28 Provides custom display name for test class or method
INLINE_CODE_29 Disables a test class or method
INLINE_CODE_30 Disables with explanation message
INLINE_CODE_31 Denotes a nested test class for organizing tests
INLINE_CODE_32 Tags tests for filtering (e.g., "slow", "integration")
INLINE_CODE_33 Repeats test execution n times
INLINE_CODE_34 Marks a method as a dynamic test factory
INLINE_CODE_35 Changes test instance lifecycle
INLINE_CODE_36 Fails test if execution exceeds 5 seconds
INLINE_CODE_37 Specifies test execution order when using INLINE_CODE_38
_
Grundlegende Hinweise
Assertion Description
INLINE_CODE_39 Asserts that two values are equal
INLINE_CODE_40 Asserts equality with custom failure message
INLINE_CODE_41 Asserts floating-point equality within delta
INLINE_CODE_42 Asserts that two values are not equal
INLINE_CODE_43 Asserts that condition is true
INLINE_CODE_44 Asserts that condition is false
INLINE_CODE_45 Asserts that object is null
INLINE_CODE_46 Asserts that object is not null
INLINE_CODE_47 Asserts that two references point to same object
INLINE_CODE_48 Asserts that two references point to different objects
INLINE_CODE_49 Asserts that two arrays are equal
INLINE_CODE_50 Asserts that two iterables are equal
INLINE_CODE_51 Asserts that two lists of strings match (supports regex)
INLINE_CODE_52 Explicitly fails a test with message
INLINE_CODE_53 Groups multiple assertions (all execute even if some fail)
_
In den Warenkorb
Assertion Description
INLINE_CODE_54 Asserts that executable throws specified exception
INLINE_CODE_55 Asserts that executable does not throw any exception
INLINE_CODE_56 Asserts that execution completes within timeout
INLINE_CODE_57 Asserts timeout and aborts execution if exceeded
INLINE_CODE_58 Asserts that object is instance of specified class
INLINE_CODE_59 Executes all assertions and reports all failures
_
Parameterierte Testannotationen
Annotation Description
INLINE_CODE_60 Marks method as parameterized test
INLINE_CODE_61 Provides array of literal values as parameters
INLINE_CODE_62 Provides array of string values
INLINE_CODE_63 Provides CSV data as parameters
INLINE_CODE_64 Loads parameters from CSV file
INLINE_CODE_65 Uses method return value as parameter source
INLINE_CODE_66 Uses enum values as parameters
INLINE_CODE_67 Provides null as parameter
INLINE_CODE_68 Provides empty value (String, Collection, Array)
INLINE_CODE_69 Combines @NullSource and @EmptySource
INLINE_CODE_70 Uses custom ArgumentsProvider implementation
_
Maven Befehle
Command Description
INLINE_CODE_71 Runs all tests in the project
INLINE_CODE_72 Runs specific test class
INLINE_CODE_73 Runs specific test method
INLINE_CODE_74 Runs all classes matching pattern
INLINE_CODE_75 Runs multiple specific test classes
INLINE_CODE_76 Cleans previous builds and runs tests
INLINE_CODE_77 Skips test execution
INLINE_CODE_78 Skips test compilation and execution
INLINE_CODE_79 Runs tests in debug mode (port 5005)
INLINE_CODE_80 Runs only tests tagged with "integration"
INLINE_CODE_81 Excludes tests tagged with "slow"
INLINE_CODE_82 Generates HTML test report
INLINE_CODE_83 Runs tests and generates code coverage report
INLINE_CODE_84 Runs tests and integration tests
INLINE_CODE_85 Reruns failing tests up to 2 times
_
Befehle der Gradle
Command Description
INLINE_CODE_86 Runs all tests
INLINE_CODE_87 Runs tests using Gradle wrapper
INLINE_CODE_88 Runs specific test class
INLINE_CODE_89 Runs specific test method
INLINE_CODE_90 Runs all classes matching pattern
INLINE_CODE_91 Cleans and runs tests
INLINE_CODE_92 Runs tests continuously on file changes
INLINE_CODE_93 Runs tests with detailed output
INLINE_CODE_94 Runs tests with debug logging
INLINE_CODE_95 Forces test rerun even if up-to-date
INLINE_CODE_96 Stops execution after first test failure
INLINE_CODE_97 Runs tests in parallel
INLINE_CODE_98 Runs tests and generates coverage report
_
Konfiguration

Maven Surefire Plugin Konfiguration

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <version>3.2.2</version>
    <configuration>
        <!-- Include/exclude test patterns -->
        <includes>
            <include>**/*Test.java</include>
            <include>**/*Tests.java</include>
        </includes>
        <excludes>
            <exclude>**/*IntegrationTest.java</exclude>
        </excludes>

        <!-- Parallel execution -->
        <parallel>methods</parallel>
        <threadCount>4</threadCount>

        <!-- Tag filtering -->
        <groups>unit, integration</groups>
        <excludedGroups>slow</excludedGroups>

        <!-- System properties -->
        <systemPropertyVariables>
            <env>test</env>
        </systemPropertyVariables>
    </configuration>
</plugin>

Gradle Test Konfiguration

test {
    useJUnitPlatform {
        // Include/exclude tags
        includeTags 'unit', 'integration'
        excludeTags 'slow'

        // Include/exclude engines
        includeEngines 'junit-jupiter'
        excludeEngines 'junit-vintage'
    }

    // Parallel execution
    maxParallelForks = 4

    // Test filtering
    filter {
        includeTestsMatching '*Test'
        excludeTestsMatching '*IntegrationTest'
    }

    // System properties
    systemProperty 'env', 'test'

    // Test logging
    testLogging {
        events "passed", "skipped", "failed"
        exceptionFormat "full"
        showStandardStreams = true
    }

    // Fail fast
    failFast = true
}

JUnit Platform Properties (junit-platform.properties)

# Parallel execution
junit.jupiter.execution.parallel.enabled = true
junit.jupiter.execution.parallel.mode.default = concurrent
junit.jupiter.execution.parallel.config.strategy = fixed
junit.jupiter.execution.parallel.config.fixed.parallelism = 4

# Test instance lifecycle
junit.jupiter.testinstance.lifecycle.default = per_class

# Display name generation
junit.jupiter.displayname.generator.default = org.junit.jupiter.api.DisplayNameGenerator$ReplaceUnderscores

# Automatic extension detection
junit.jupiter.extensions.autodetection.enabled = true

# Deactivate conditions
junit.jupiter.conditions.deactivate = org.junit.*DisabledCondition

Häufige Anwendungsfälle

Use Case: Basic Unit Test mit Setup und Teardown

import org.junit.jupiter.api.*;
import static org.junit.jupiter.api.Assertions.*;

class UserServiceTest {
    private UserService userService;
    private Database mockDb;

    @BeforeEach
    void setUp() {
        mockDb = new MockDatabase();
        userService = new UserService(mockDb);
    }

    @Test
    @DisplayName("Should create user with valid data")
    void testCreateUser() {
        User user = new User("john@example.com", "password123");
        User created = userService.createUser(user);

        assertNotNull(created.getId());
        assertEquals("john@example.com", created.getEmail());
    }

    @AfterEach
    void tearDown() {
        mockDb.close();
    }
}

Use Case: Parameterisierte Prüfung für mehrere Eingänge

import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.*;

class CalculatorTest {

    @ParameterizedTest
    @CsvSource({
        "1, 1, 2",
        "2, 3, 5",
        "10, -5, 5",
        "0, 0, 0"
    })
    void testAddition(int a, int b, int expected) {
        Calculator calc = new Calculator();
        assertEquals(expected, calc.add(a, b));
    }

    @ParameterizedTest
    @ValueSource(strings = {"", "  ", "\t", "\n"})
    void testBlankStrings(String input) {
        assertTrue(StringUtils.isBlank(input));
    }

    @ParameterizedTest
    @MethodSource("provideEmailTestCases")
    void testEmailValidation(String email, boolean expected) {
        assertEquals(expected, EmailValidator.isValid(email));
    }

    static Stream<Arguments> provideEmailTestCases() {
        return Stream.of(
            Arguments.of("test@example.com", true),
            Arguments.of("invalid.email", false),
            Arguments.of("@example.com", false)
        );
    }
}

Use Case: Ausnahmeprüfung und Timeout Verification

import org.junit.jupiter.api.Test;
import java.time.Duration;
import static org.junit.jupiter.api.Assertions.*;

class PaymentServiceTest {

    @Test
    void shouldThrowExceptionForInvalidAmount() {
        PaymentService service = new PaymentService();

        Exception exception = assertThrows(
            IllegalArgumentException.class,
            () -> service.processPayment(-100)
        );

        assertEquals("Amount must be positive", exception.getMessage());
    }

    @Test
    void shouldCompleteWithinTimeout() {
        PaymentService service = new PaymentService();

        assertTimeout(Duration.ofSeconds(2), () -> {
            service.processPayment(100);
        });
    }

    @Test
    void shouldNotThrowExceptionForValidPayment() {
        PaymentService service = new PaymentService();

        assertDoesNotThrow(() -> {
            service.processPayment(100);
        });
    }
}

Use Case: Eingebettete Tests für Organisierte Teststruktur

import org.junit.jupiter.api.*;

@DisplayName("Shopping Cart Tests")
class ShoppingCartTest {

    @Nested
    @DisplayName("When cart is empty")
    class EmptyCart {
        private ShoppingCart cart;

        @BeforeEach
        void setUp() {
            cart = new ShoppingCart();
        }

        @Test
        @DisplayName("Should have zero items")
        void testItemCount() {
            assertEquals(0, cart.getItemCount());
        }

        @Test
        @DisplayName("Should have zero total")
        void testTotal() {
            assertEquals(0.0, cart.getTotal());
        }
    }

    @Nested
    @DisplayName("When cart has items")
    class CartWithItems {
        private ShoppingCart cart;

        @BeforeEach
        void setUp() {
            cart = new ShoppingCart();
            cart.addItem(new Item("Book", 29.99));
            cart.addItem(new Item("Pen", 2.50));
        }

        @Test
        @DisplayName("Should calculate correct total")
        void testTotal() {
            assertEquals(32.49, cart.getTotal(), 0.01);
        }

        @Test
        @DisplayName("Should allow item removal")
        void testRemoveItem() {
            cart.removeItem(0);
            assertEquals(1, cart.getItemCount());
        }
    }
}

Use Case: Integrationstest mit Test Lifecycle Management

import org.junit.jupiter.api.*;

@TestInstance(TestInstance.Lifecycle.PER_CLASS)
class DatabaseIntegrationTest {
    private static DatabaseConnection connection;
    private UserRepository userRepository;

    @BeforeAll
    void setUpDatabase() {
        // Expensive one-time setup
        connection = DatabaseConnection.connect("jdbc:h2:mem:test");
        connection.runMigrations();
    }

    @BeforeEach
    void setUp() {
        userRepository = new UserRepository(connection);
        connection.beginTransaction();
    }

    @Test
    @Tag("integration")
    void testUserPersistence() {
        User user = new User("test@example.com");
        userRepository.save(user);

        User retrieved = userRepository.findById(user.getId());
        assertEquals(user.getEmail(), retrieved.getEmail());
    }

    @AfterEach
    void tearDown() {
        connection.rollbackTransaction();
    }

    @AfterAll
    void tearDownDatabase() {
        connection.close();
    }
}

oder Best Practices

**Benutze beschreibende Testnamen*: Leverage @DisplayName_, um Testzwecke klar zu machen. Testnamen sollten beschreiben, was getestet wird und das erwartete Ergebnis (z.B. "Soll werfen Ausnahme, wenn Menge negativ ist").

  • **Folge AAA Muster*: Strukturtests mit Arrange (Setup), Act (execute), und Assert (verify) Abschnitte zur Klarheit und Aufrechterhaltungsfähigkeit.

  • Testen Sie eine Sache pro Test**: Jede Testmethode sollte ein einzelnes Verhalten oder Szenario überprüfen. Dies erleichtert die Diagnose und die Tests einfacher zu halten.

  • BeforeEach und @AfterEach klug: Initialisieren Sie gemeinsame Testgeräte in __INLINE_CODE_100_, aber vermeiden Sie übermäßige Setup, die Tests schwer zu verstehen macht. Ressourcen aufräumen @AfterEach.

  • **Prefer @Parameterisiert Test für mehrere ähnliche Fälle*: Anstatt mehrere ähnliche Testmethoden zu schreiben, verwenden Sie parametrierte Tests, um dieselbe Logik mit unterschiedlichen Eingängen zu testen.

  • **Benutzen Sie alles für verwandte Behauptungen*: Group verwandte Behauptungen mit assertAll(), um alle Fehler sofort zu sehen, anstatt beim ersten Ausfall zu stoppen.

  • **Tag-Tests entsprechend*: Verwenden Sie __INLINE_CODE_103_, um Tests (Einheit, Integration, langsam) zu kategorisieren, so dass Sie selektiv Testsuiten in verschiedenen Umgebungen oder CI/CD-Stufen ausführen können.

  • **Avoid Testinterdependancen*: Tests sollten unabhängig sein und in jeder Reihenfolge laufen können. verlassen Sie sich nie auf Ausführungsauftrag oder Zustand von anderen Tests.

  • ** Nutze aussagekräftige Durchsetzungsnachrichten*: Bieten Sie benutzerdefinierte Fehlernachrichten an, um das Debugging zu erleichtern: assertEquals(expected, actual, "User email should match").

  • **Keep-Tests schnell*: Einheitentests sollten schnell durchgeführt werden. Bewegen Sie langsame Tests (Datenbank, Netzwerk), um Integrationstest-Suiten mit Tags oder separaten Quell-Sets zu trennen.

Fehlerbehebung

Issue Solution
Tests not discovered/running Ensure test methods are INLINE_CODE_105 or package-private, annotated with INLINE_CODE_106, and class names match pattern INLINE_CODE_107 or INLINE_CODE_108. For Maven, verify surefire plugin version ≥ 2.22.0 for JUnit 5 support.
NoClassDefFoundError for JUnit classes Add JUnit dependency with INLINE_CODE_109 in Maven or INLINE_CODE_110 in Gradle. Verify correct JUnit version (5.x for Jupiter, 4.x for legacy).
@BeforeAll/@AfterAll must be static error Methods with INLINE_CODE_111/INLINE_CODE_112 must be INLINE_CODE_113 unless using INLINE_CODE_114 on the test class.
Parameterized tests not running Add INLINE_CODE_115 dependency: INLINE_CODE_116. Ensure method has INLINE_CODE_117 instead of INLINE_CODE_118.
Tests pass in IDE but fail in Maven/Gradle Check for different JUnit versions between IDE and build tool. Verify INLINE_CODE_119 version ≥ 2.22.0 or Gradle has INLINE_CODE_120 in test configuration.
Assertion methods not found Import static assertion methods: INLINE_CODE_121 for JUnit 5 or INLINE_CODE_122 for JUnit 4.
Tests run but results not displayed For Maven, check surefire reports in INLINE_CODE_123. For Gradle, check INLINE_CODE_124 or add INLINE_CODE_125 configuration.
Timeout tests failing unexpectedly Use INLINE_CODE_126 instead of INLINE_CODE_127 if test code doesn't respect interruption. Check for blocking I/O or synchronization issues.
Cannot mix JUnit 4 and JUnit 5 annotations Use JUnit Vintage engine to run JUnit 4 tests alongside JUnit 5, or migrate all tests to JUnit 5. Add INLINE_CODE_128 dependency for backward compatibility.
Gradle-Tests immer UP-TO-DATE* Verwenden Sie gradle cleanTest test oder gradle test --rerun-tasks, um die Testausführung zu erzwingen. Prüfen Sie, ob die Testquellendateien im korrekten Verzeichnis (INLINE_CODE_131__) enthalten sind.