Testing / JUnit6 Interview Questions
What are tags and filtering in JUnit 6 and how are they used?
Tags categorise tests. At build time you can include or exclude specific tags, enabling selective test execution (e.g. run only fast tests in a pre-commit hook, all tests in CI).
// Annotate tests with @Tag @Tag("fast") @Tag("unit") class FastUnitTest { @Test void test1() { ... } } @Tag("slow") @Tag("integration") class SlowIntegrationTest { @Test void dbTest() { ... } } // Composed annotation to avoid repetition: @Target({ElementType.TYPE, ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) @Tag("fast") @Tag("unit") public @interface UnitTest { } @UnitTest // same as @Tag("fast") @Tag("unit") class OrderServiceTest { ... }
<!-- Maven Surefire: run only fast unit tests --> <plugin> <artifactId>maven-surefire-plugin</artifactId> <version>3.3.0</version> <configuration> <groups>fast & unit</groups> <excludedGroups>slow | integration</excludedGroups> </configuration> </plugin> <!-- ConsoleLauncher: tag expression syntax --> java -jar junit-platform-console-standalone-6.1.1.jar \ --scan-class-path \ --include-tag "fast" \ --exclude-tag "slow" # Gradle: filter by tag test { useJUnitPlatform { includeTags "fast" excludeTags "slow", "integration" } }
More Related questions...