From 81faf1892de3c25a2e85bee44b317f9b6fef472d Mon Sep 17 00:00:00 2001 From: Daniel Teuchert Date: Wed, 15 Jul 2026 17:14:40 +0200 Subject: [PATCH 1/2] Fix S5738: Replace deprecated @EnableRuleMigrationSupport with JUnit 5 native APIs Migrate 12 test files from JUnit 4 @Rule/TemporaryFolder to JUnit 5 @TempDir Path, and drop @EnableRuleMigrationSupport (marked for removal). Helper methods in InputFileUtils and ExternalReportTestUtils updated to accept Path instead of TemporaryFolder. LogTester @Rule removed from doc example tests where it was unused in assertions. Co-Authored-By: Claude Sonnet 4.6 (1M context) --- .../AvoidBrandInMethodNamesRuleTest.java | 9 ----- .../SecurityAnnotationMandatoryRuleTest.java | 9 ----- .../externalreport/CheckstyleSensorTest.java | 9 ++--- .../ExternalReportTestUtils.java | 5 +-- .../externalreport/SpotBugsSensorTest.java | 9 ++--- .../java/checks/verifier/FilesUtilsTest.java | 12 +++--- .../org/sonar/java/BatchGeneratorTest.java | 16 ++++---- .../java/org/sonar/java/InputFileUtils.java | 8 ++-- .../java/org/sonar/java/JavaFrontendTest.java | 28 +++++++------ .../visitors/SonarSymbolTableVisitorTest.java | 12 +++--- .../SyntaxHighlighterVisitorTest.java | 14 +++---- .../java/model/JParserReleasingJarsTest.java | 13 +++---- .../java/DroppedPropertiesSensorTest.java | 18 ++++----- .../sonar/plugins/java/JavaSensorTest.java | 39 +++++++++---------- 14 files changed, 80 insertions(+), 121 deletions(-) diff --git a/docs/java-custom-rules-example/src/test/java/org/sonar/samples/java/checks/AvoidBrandInMethodNamesRuleTest.java b/docs/java-custom-rules-example/src/test/java/org/sonar/samples/java/checks/AvoidBrandInMethodNamesRuleTest.java index e093784bc23..3fb4f5766c1 100644 --- a/docs/java-custom-rules-example/src/test/java/org/sonar/samples/java/checks/AvoidBrandInMethodNamesRuleTest.java +++ b/docs/java-custom-rules-example/src/test/java/org/sonar/samples/java/checks/AvoidBrandInMethodNamesRuleTest.java @@ -4,20 +4,11 @@ */ package org.sonar.samples.java.checks; -import org.junit.Rule; import org.junit.jupiter.api.Test; -import org.junit.jupiter.migrationsupport.rules.EnableRuleMigrationSupport; -import org.slf4j.event.Level; -import org.sonar.api.testfixtures.log.LogTester; import org.sonar.java.checks.verifier.CheckVerifier; -@EnableRuleMigrationSupport class AvoidBrandInMethodNamesRuleTest { - // Set a LogTester to see the Syntax Tree when running tests and executing the rule - @Rule - public LogTester logTester = new LogTester().setLevel(Level.DEBUG); - @Test void detected() { // Verifies that the check will raise the adequate issues with the expected message. diff --git a/docs/java-custom-rules-example/src/test/java/org/sonar/samples/java/checks/SecurityAnnotationMandatoryRuleTest.java b/docs/java-custom-rules-example/src/test/java/org/sonar/samples/java/checks/SecurityAnnotationMandatoryRuleTest.java index e5201da5531..40bd9574119 100644 --- a/docs/java-custom-rules-example/src/test/java/org/sonar/samples/java/checks/SecurityAnnotationMandatoryRuleTest.java +++ b/docs/java-custom-rules-example/src/test/java/org/sonar/samples/java/checks/SecurityAnnotationMandatoryRuleTest.java @@ -4,20 +4,11 @@ */ package org.sonar.samples.java.checks; -import org.junit.Rule; import org.junit.jupiter.api.Test; -import org.junit.jupiter.migrationsupport.rules.EnableRuleMigrationSupport; -import org.slf4j.event.Level; -import org.sonar.api.testfixtures.log.LogTester; import org.sonar.java.checks.verifier.CheckVerifier; -@EnableRuleMigrationSupport class SecurityAnnotationMandatoryRuleTest { - // Set a LogTester to see the Syntax Tree when running tests and executing the rule - @Rule - public LogTester logTester = new LogTester().setLevel(Level.DEBUG); - @Test void detected() { // Use an instance of the check under test to raise the issue. diff --git a/external-reports/src/test/java/org/sonar/java/externalreport/CheckstyleSensorTest.java b/external-reports/src/test/java/org/sonar/java/externalreport/CheckstyleSensorTest.java index 61e831e79af..28aefd3c077 100644 --- a/external-reports/src/test/java/org/sonar/java/externalreport/CheckstyleSensorTest.java +++ b/external-reports/src/test/java/org/sonar/java/externalreport/CheckstyleSensorTest.java @@ -23,13 +23,11 @@ import java.util.ArrayList; import java.util.List; import javax.annotation.Nullable; -import org.junit.Rule; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; -import org.junit.jupiter.migrationsupport.rules.EnableRuleMigrationSupport; +import org.junit.jupiter.api.io.TempDir; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; -import org.junit.rules.TemporaryFolder; import org.slf4j.event.Level; import org.sonar.api.batch.rule.Severity; import org.sonar.api.batch.sensor.internal.DefaultSensorDescriptor; @@ -42,7 +40,6 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.sonar.java.externalreport.ExternalReportTestUtils.onlyOneLogElement; -@EnableRuleMigrationSupport class CheckstyleSensorTest { private static final Path PROJECT_DIR = Paths.get("src", "test", "resources", "checkstyle") @@ -51,8 +48,8 @@ class CheckstyleSensorTest { private static SensorContextTester sensorContext = SensorContextTester.create(PROJECT_DIR); private static CheckstyleSensor checkstyleSensor = new CheckstyleSensor(sensorContext.runtime()); - @Rule - public final TemporaryFolder tmp = new TemporaryFolder(); + @TempDir + Path tmp; @RegisterExtension public LogTesterJUnit5 logTester = new LogTesterJUnit5().setLevel(Level.DEBUG); diff --git a/external-reports/src/test/java/org/sonar/java/externalreport/ExternalReportTestUtils.java b/external-reports/src/test/java/org/sonar/java/externalreport/ExternalReportTestUtils.java index c7a4a2eda07..dcc8bc29b3c 100644 --- a/external-reports/src/test/java/org/sonar/java/externalreport/ExternalReportTestUtils.java +++ b/external-reports/src/test/java/org/sonar/java/externalreport/ExternalReportTestUtils.java @@ -22,7 +22,6 @@ import java.nio.file.Path; import java.util.List; import java.util.stream.Stream; -import org.junit.rules.TemporaryFolder; import org.slf4j.event.Level; import org.sonar.api.batch.fs.InputFile; import org.sonar.api.batch.fs.internal.TestInputFileBuilder; @@ -50,14 +49,14 @@ public static String onlyOneLogElement(List elements) { return elements.get(0); } - public static File generateReport(Path projectDir, TemporaryFolder tmp, String fileName) throws IOException { + public static File generateReport(Path projectDir, Path tmp, String fileName) throws IOException { Path filePath = projectDir.resolve(fileName); if (!filePath.toFile().exists()) { return filePath.toFile(); } String reportData = new String(Files.readAllBytes(filePath), UTF_8); reportData = reportData.replace("${PROJECT_DIR}", projectDir.toRealPath() + File.separator); - File reportFile = tmp.newFile(fileName).getCanonicalFile(); + File reportFile = tmp.resolve(fileName).toFile().getCanonicalFile(); Files.write(reportFile.toPath(), reportData.getBytes(UTF_8)); return reportFile; } diff --git a/external-reports/src/test/java/org/sonar/java/externalreport/SpotBugsSensorTest.java b/external-reports/src/test/java/org/sonar/java/externalreport/SpotBugsSensorTest.java index 91240420948..58c75a34a2e 100644 --- a/external-reports/src/test/java/org/sonar/java/externalreport/SpotBugsSensorTest.java +++ b/external-reports/src/test/java/org/sonar/java/externalreport/SpotBugsSensorTest.java @@ -23,13 +23,11 @@ import java.util.ArrayList; import java.util.List; import javax.annotation.Nullable; -import org.junit.Rule; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; -import org.junit.jupiter.migrationsupport.rules.EnableRuleMigrationSupport; +import org.junit.jupiter.api.io.TempDir; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; -import org.junit.rules.TemporaryFolder; import org.slf4j.event.Level; import org.sonar.api.batch.rule.Severity; import org.sonar.api.batch.sensor.internal.DefaultSensorDescriptor; @@ -43,7 +41,6 @@ import static org.assertj.core.api.Assertions.tuple; import static org.sonar.java.externalreport.ExternalReportTestUtils.onlyOneLogElement; -@EnableRuleMigrationSupport class SpotBugsSensorTest { private static final Path PROJECT_DIR = Paths.get("src", "test", "resources", "spotbugs") @@ -52,8 +49,8 @@ class SpotBugsSensorTest { private static SensorContextTester sensorContext = SensorContextTester.create(PROJECT_DIR); private static SpotBugsSensor spotBugsSensor = new SpotBugsSensor(sensorContext.runtime()); - @Rule - public final TemporaryFolder tmp = new TemporaryFolder(); + @TempDir + Path tmp; @RegisterExtension public LogTesterJUnit5 logTester = new LogTesterJUnit5().setLevel(Level.DEBUG); diff --git a/java-checks-testkit/src/test/java/org/sonar/java/checks/verifier/FilesUtilsTest.java b/java-checks-testkit/src/test/java/org/sonar/java/checks/verifier/FilesUtilsTest.java index ddd5acc1078..5c91778987e 100644 --- a/java-checks-testkit/src/test/java/org/sonar/java/checks/verifier/FilesUtilsTest.java +++ b/java-checks-testkit/src/test/java/org/sonar/java/checks/verifier/FilesUtilsTest.java @@ -22,19 +22,17 @@ import java.nio.file.Path; import java.util.List; import org.junit.jupiter.api.Test; -import org.junit.jupiter.migrationsupport.rules.EnableRuleMigrationSupport; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.io.TempDir; import static org.assertj.core.api.Assertions.assertThat; -@EnableRuleMigrationSupport class FilesUtilsTest { - @org.junit.Rule - public TemporaryFolder temp = new TemporaryFolder(); + @TempDir + Path temp; @Test void verify_get_classpath_files() throws IOException { - Path tmp = temp.newFolder().toPath(); + Path tmp = Files.createTempDirectory(temp, ""); Path jar = tmp.resolve("test.jar"); Path zip = tmp.resolve("test.zip"); Path invalid = tmp.resolve("test.txt"); @@ -43,7 +41,7 @@ void verify_get_classpath_files() throws IOException { Files.createFile(zip); Files.createFile(invalid); - List list = FilesUtils.getFilesRecursively(temp.getRoot().toPath(), new String[] {"zip", "jar"}); + List list = FilesUtils.getFilesRecursively(temp, new String[] {"zip", "jar"}); assertThat(list).containsOnly(jar.toFile(), zip.toFile()); } diff --git a/java-frontend/src/test/java/org/sonar/java/BatchGeneratorTest.java b/java-frontend/src/test/java/org/sonar/java/BatchGeneratorTest.java index 9834646fb1b..71fd2fdfffb 100644 --- a/java-frontend/src/test/java/org/sonar/java/BatchGeneratorTest.java +++ b/java-frontend/src/test/java/org/sonar/java/BatchGeneratorTest.java @@ -18,14 +18,13 @@ import java.io.File; import java.io.IOException; +import java.nio.file.Path; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; -import org.junit.Rule; import org.junit.jupiter.api.Test; -import org.junit.jupiter.migrationsupport.rules.EnableRuleMigrationSupport; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.io.TempDir; import org.sonar.api.batch.fs.InputFile; import org.sonar.api.batch.sensor.internal.SensorContextTester; import org.sonar.api.config.internal.MapSettings; @@ -33,10 +32,9 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.sonar.java.InputFileUtils.addFile; -@EnableRuleMigrationSupport class BatchGeneratorTest { - @Rule - public TemporaryFolder temp = new TemporaryFolder(); + @TempDir + Path temp; @Test void batch_generator_returns_an_empty_list_when_no_input_files() { @@ -48,7 +46,7 @@ void batch_generator_returns_an_empty_list_when_no_input_files() { @Test void batch_generator_returns_at_most_one_item_per_batch_when_size_is_zero() throws IOException { - File baseDir = temp.getRoot().getAbsoluteFile(); + File baseDir = temp.toFile().getAbsoluteFile(); SensorContextTester sensorContext = SensorContextTester.create(baseDir); sensorContext.setSettings(new MapSettings()); List inputFiles = new ArrayList<>(); @@ -69,7 +67,7 @@ void batch_generator_returns_at_most_one_item_per_batch_when_size_is_zero() thro @Test void batch_generator_returns_batches_with_multiple_files_that_are_smaller_than_batch_size() throws IOException { - File baseDir = temp.getRoot().getAbsoluteFile(); + File baseDir = temp.toFile().getAbsoluteFile(); SensorContextTester sensorContext = SensorContextTester.create(baseDir); sensorContext.setSettings(new MapSettings()); InputFile fileA = addFile(temp, "class A { public void doSomething() {} }", sensorContext); @@ -107,7 +105,7 @@ void batch_generator_returns_batches_with_multiple_files_that_are_smaller_than_b @Test void batch_generator_includes_file_excluded_from_previous_batch_into_next_batch() throws IOException { - File baseDir = temp.getRoot().getAbsoluteFile(); + File baseDir = temp.toFile().getAbsoluteFile(); SensorContextTester sensorContext = SensorContextTester.create(baseDir); sensorContext.setSettings(new MapSettings()); InputFile fileA = addFile(temp, "class A { public void doSomething() {} }", sensorContext); diff --git a/java-frontend/src/test/java/org/sonar/java/InputFileUtils.java b/java-frontend/src/test/java/org/sonar/java/InputFileUtils.java index 08e6fd9d9ad..9406971cbe8 100644 --- a/java-frontend/src/test/java/org/sonar/java/InputFileUtils.java +++ b/java-frontend/src/test/java/org/sonar/java/InputFileUtils.java @@ -20,23 +20,23 @@ import java.io.File; import java.io.IOException; import java.nio.charset.StandardCharsets; +import java.nio.file.Path; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.jetbrains.annotations.NotNull; -import org.junit.rules.TemporaryFolder; import org.sonar.api.batch.fs.InputFile; import org.sonar.api.batch.sensor.internal.SensorContextTester; class InputFileUtils { - public static InputFile addFile(TemporaryFolder temp, String code, SensorContextTester context) throws IOException { + public static InputFile addFile(Path temp, String code, SensorContextTester context) throws IOException { Matcher matcher = Pattern.compile("(?:^|\\s)(?:class|interface|enum|record)\\s++(\\w++)").matcher(code); if (matcher.find()) { String className = matcher.group(1); InputFile.Type type = className.endsWith("Test") ? InputFile.Type.TEST : InputFile.Type.MAIN; - File file = temp.newFile(className + ".java").getAbsoluteFile(); + File file = temp.resolve(className + ".java").toFile().getAbsoluteFile(); return generateInputFile(code, context, file, type); } else { - File file = temp.newFile("Unnamed.java").getAbsoluteFile(); + File file = temp.resolve("Unnamed.java").toFile().getAbsoluteFile(); return generateInputFile(code, context, file, InputFile.Type.MAIN); } } diff --git a/java-frontend/src/test/java/org/sonar/java/JavaFrontendTest.java b/java-frontend/src/test/java/org/sonar/java/JavaFrontendTest.java index 9878e64b678..411d3059517 100644 --- a/java-frontend/src/test/java/org/sonar/java/JavaFrontendTest.java +++ b/java-frontend/src/test/java/org/sonar/java/JavaFrontendTest.java @@ -18,18 +18,17 @@ import java.io.File; import java.io.IOException; +import java.nio.file.Path; import java.util.ArrayList; import java.util.Collections; import java.util.List; import javax.annotation.Nullable; import org.eclipse.core.runtime.OperationCanceledException; -import org.junit.Rule; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; -import org.junit.jupiter.migrationsupport.rules.EnableRuleMigrationSupport; +import org.junit.jupiter.api.io.TempDir; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; -import org.junit.rules.TemporaryFolder; import org.slf4j.event.Level; import org.sonar.api.SonarEdition; import org.sonar.api.SonarQubeSide; @@ -83,7 +82,6 @@ import static org.sonar.java.InputFileUtils.addFile; import static org.sonar.java.TestUtils.mockSonarComponents; -@EnableRuleMigrationSupport class JavaFrontendTest { @@ -95,8 +93,8 @@ class JavaFrontendTest { private static final Version LATESTS_SONAR_API_VERSION = Version.create(8, 13); public static final SonarRuntime SONARQUBE_RUNTIME = SonarRuntimeImpl.forSonarQube(LATESTS_SONAR_API_VERSION, SonarQubeSide.SCANNER, SonarEdition.COMMUNITY); - @Rule - public TemporaryFolder temp = new TemporaryFolder(); + @TempDir + Path temp; @RegisterExtension public LogTesterJUnit5 logTester = new LogTesterJUnit5().setLevel(Level.DEBUG); @@ -211,7 +209,7 @@ public void scanFile(JavaFileScannerContext context) { var settings = new MapSettings(); if (sensorContext == null) { - File baseDir = temp.getRoot().getAbsoluteFile(); + File baseDir = temp.toFile().getAbsoluteFile(); sensorContext = SensorContextTester.create(baseDir); sensorContext.setSettings(settings); } @@ -239,7 +237,7 @@ void scanning_empty_project_should_be_logged_in_autoscan() { @Test void test_scan_logs_when_caching_is_enabled_and_can_skip_unchanged_files() throws ApiMismatchException { - File baseDir = temp.getRoot().getAbsoluteFile(); + File baseDir = temp.toFile().getAbsoluteFile(); SensorContextTester sensorContextTester = SensorContextTester.create(baseDir); sensorContextTester.setSettings(new MapSettings()); @@ -273,7 +271,7 @@ void test_scan_logs_when_caching_is_enabled_and_can_skip_unchanged_files() throw @Test void test_scan_logs_when_caching_is_enabled_and_cannot_skip_unchanged_files() throws ApiMismatchException { - File baseDir = temp.getRoot().getAbsoluteFile(); + File baseDir = temp.toFile().getAbsoluteFile(); SensorContextTester sensorContextTester = SensorContextTester.create(baseDir); sensorContextTester.setSettings(new MapSettings()); @@ -307,7 +305,7 @@ void test_scan_logs_when_caching_is_enabled_and_cannot_skip_unchanged_files() th @Test void test_scan_logs_when_caching_is_enabled_and_cannot_determine_if_unchanged_files_can_be_skipped() throws ApiMismatchException { - File baseDir = temp.getRoot().getAbsoluteFile(); + File baseDir = temp.toFile().getAbsoluteFile(); SensorContextTester sensorContextTester = SensorContextTester.create(baseDir); sensorContextTester.setSettings(new MapSettings()); @@ -341,7 +339,7 @@ void test_scan_logs_when_caching_is_enabled_and_cannot_determine_if_unchanged_fi @Test void test_scan_logs_when_caching_is_disabled_and_can_skip_unchanged_files() throws ApiMismatchException { - File baseDir = temp.getRoot().getAbsoluteFile(); + File baseDir = temp.toFile().getAbsoluteFile(); SensorContextTester sensorContextTester = SensorContextTester.create(baseDir); sensorContextTester.setSettings(new MapSettings()); @@ -374,7 +372,7 @@ void test_scan_logs_when_caching_is_disabled_and_can_skip_unchanged_files() thro @Test void test_scan_logs_when_caching_is_disabled_and_cannot_skip_unchanged_files() throws ApiMismatchException { - File baseDir = temp.getRoot().getAbsoluteFile(); + File baseDir = temp.toFile().getAbsoluteFile(); SensorContextTester sensorContextTester = SensorContextTester.create(baseDir); sensorContextTester.setSettings(new MapSettings()); @@ -407,7 +405,7 @@ void test_scan_logs_when_caching_is_disabled_and_cannot_skip_unchanged_files() t @Test void test_scan_logs_when_caching_is_disabled_when_sonar_components_is_null() { - File baseDir = temp.getRoot().getAbsoluteFile(); + File baseDir = temp.toFile().getAbsoluteFile(); SensorContextTester sensorContextTester = SensorContextTester.create(baseDir); sensorContextTester.setSettings(new MapSettings()); @@ -751,7 +749,7 @@ private List scan(SonarRuntime sonarRuntime, String... codeList) thro private List scan(MapSettings settings, SonarRuntime sonarRuntime, String... codeList) throws IOException { if (sensorContext == null) { - File baseDir = temp.getRoot().getAbsoluteFile(); + File baseDir = temp.toFile().getAbsoluteFile(); sensorContext = SensorContextTester.create(baseDir); sensorContext.setSettings(settings); } @@ -768,7 +766,7 @@ private List scan(MapSettings settings, SonarRuntime sonarRuntime, Li private List scan(MapSettings settings, SonarRuntime sonarRuntime, List inputFiles, @Nullable CheckRegistrar[] checkRegistrars) { if (sensorContext == null) { - File baseDir = temp.getRoot().getAbsoluteFile(); + File baseDir = temp.toFile().getAbsoluteFile(); sensorContext = SensorContextTester.create(baseDir); sensorContext.setSettings(settings); } diff --git a/java-frontend/src/test/java/org/sonar/java/ast/visitors/SonarSymbolTableVisitorTest.java b/java-frontend/src/test/java/org/sonar/java/ast/visitors/SonarSymbolTableVisitorTest.java index ca45f4f7938..cf6b6c875df 100644 --- a/java-frontend/src/test/java/org/sonar/java/ast/visitors/SonarSymbolTableVisitorTest.java +++ b/java-frontend/src/test/java/org/sonar/java/ast/visitors/SonarSymbolTableVisitorTest.java @@ -17,13 +17,12 @@ package org.sonar.java.ast.visitors; import java.io.File; +import java.nio.file.Path; import java.util.Collection; import java.util.Collections; -import org.junit.Rule; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import org.junit.jupiter.migrationsupport.rules.EnableRuleMigrationSupport; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.io.TempDir; import org.sonar.api.batch.fs.InputFile; import org.sonar.api.batch.fs.TextPointer; import org.sonar.api.batch.fs.TextRange; @@ -42,17 +41,16 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; -@EnableRuleMigrationSupport class SonarSymbolTableVisitorTest { - @Rule - public TemporaryFolder temp = new TemporaryFolder(); + @TempDir + Path temp; private SensorContextTester context; private SonarComponents sonarComponents; @BeforeEach void setUp() { - context = SensorContextTester.create(temp.getRoot()); + context = SensorContextTester.create(temp.toFile()); sonarComponents = new SonarComponents(mock(FileLinesContextFactory.class), context.fileSystem(), mock(ClasspathForMain.class), mock(ClasspathForTest.class), mock(CheckFactory.class), mock(ActiveRules.class)); sonarComponents.setSensorContext(context); diff --git a/java-frontend/src/test/java/org/sonar/java/ast/visitors/SyntaxHighlighterVisitorTest.java b/java-frontend/src/test/java/org/sonar/java/ast/visitors/SyntaxHighlighterVisitorTest.java index 6863b75f199..e028f2f4a3f 100644 --- a/java-frontend/src/test/java/org/sonar/java/ast/visitors/SyntaxHighlighterVisitorTest.java +++ b/java-frontend/src/test/java/org/sonar/java/ast/visitors/SyntaxHighlighterVisitorTest.java @@ -19,14 +19,13 @@ import com.google.common.io.Files; import java.io.File; import java.nio.charset.StandardCharsets; +import java.nio.file.Path; import java.util.Collections; -import org.junit.Rule; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import org.junit.jupiter.migrationsupport.rules.EnableRuleMigrationSupport; +import org.junit.jupiter.api.io.TempDir; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; -import org.junit.rules.TemporaryFolder; import org.sonar.api.batch.fs.InputFile; import org.sonar.api.batch.rule.ActiveRules; import org.sonar.api.batch.rule.CheckFactory; @@ -50,11 +49,10 @@ import static org.mockito.Mockito.verify; import static org.sonar.java.TestUtils.mockSonarComponents; -@EnableRuleMigrationSupport class SyntaxHighlighterVisitorTest { - @Rule - public TemporaryFolder temp = new TemporaryFolder(); + @TempDir + Path temp; private SensorContextTester context; private SonarComponents sonarComponents; @@ -63,7 +61,7 @@ class SyntaxHighlighterVisitorTest { @BeforeEach void setUp() { - context = SensorContextTester.create(temp.getRoot()); + context = SensorContextTester.create(temp.toFile()); sonarComponents = new SonarComponents(mock(FileLinesContextFactory.class), context.fileSystem(), mock(ClasspathForMain.class), mock(ClasspathForTest.class), mock(CheckFactory.class), mock(ActiveRules.class)); sonarComponents.setSensorContext(context); @@ -73,7 +71,7 @@ void setUp() { @Test void parse_error() throws Exception { SensorContextTester spy = spy(context); - File file = temp.newFile().getAbsoluteFile(); + File file = temp.resolve("parse_error.java").toFile().getAbsoluteFile(); Files.asCharSink(file, StandardCharsets.UTF_8).write("ParseError"); scan(TestUtils.inputFile(file)); verify(spy, never()).newHighlighting(); diff --git a/java-frontend/src/test/java/org/sonar/java/model/JParserReleasingJarsTest.java b/java-frontend/src/test/java/org/sonar/java/model/JParserReleasingJarsTest.java index f7b71f69667..24df3c160a6 100644 --- a/java-frontend/src/test/java/org/sonar/java/model/JParserReleasingJarsTest.java +++ b/java-frontend/src/test/java/org/sonar/java/model/JParserReleasingJarsTest.java @@ -18,11 +18,11 @@ import com.google.common.io.Files; import java.io.File; +import java.nio.file.Path; import java.util.Collections; import java.util.List; import org.junit.jupiter.api.Test; -import org.junit.jupiter.migrationsupport.rules.EnableRuleMigrationSupport; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.io.TempDir; import org.sonar.plugins.java.api.semantic.Symbol; import org.sonar.plugins.java.api.tree.ClassTree; import org.sonar.plugins.java.api.tree.ExpressionStatementTree; @@ -31,11 +31,10 @@ import static org.assertj.core.api.Assertions.assertThat; -@EnableRuleMigrationSupport class JParserReleasingJarsTest { - @org.junit.Rule - public TemporaryFolder temp = new TemporaryFolder(); + @TempDir + Path temp; private static final String PROJECT_JAR = "src/test/files/other/project.jar"; private static final String SOURCE = "package foo.bar;\n" @@ -75,7 +74,7 @@ void jParser_should_resolve_method_with_jar_in_classPath() { */ @Test void should_be_able_to_delete_jar() throws Exception { - File newJar = new File(temp.newFolder(), "project2.jar"); + File newJar = temp.resolve("project2.jar").toFile(); Files.copy(new File(PROJECT_JAR), newJar); assertThat(newJar).exists(); @@ -90,7 +89,7 @@ void should_be_able_to_delete_jar() throws Exception { */ @Test void jParser_should_release_jar_after_use() throws Exception { - File newJar = new File(temp.newFolder(), "project3.jar"); + File newJar = temp.resolve("project3.jar").toFile(); Files.copy(new File(PROJECT_JAR), newJar); assertThat(newJar).exists(); diff --git a/sonar-java-plugin/src/test/java/org/sonar/plugins/java/DroppedPropertiesSensorTest.java b/sonar-java-plugin/src/test/java/org/sonar/plugins/java/DroppedPropertiesSensorTest.java index f26cb49ea32..5d457a8e83f 100644 --- a/sonar-java-plugin/src/test/java/org/sonar/plugins/java/DroppedPropertiesSensorTest.java +++ b/sonar-java-plugin/src/test/java/org/sonar/plugins/java/DroppedPropertiesSensorTest.java @@ -16,13 +16,12 @@ */ package org.sonar.plugins.java; +import java.nio.file.Path; import java.util.ArrayList; import java.util.List; -import org.junit.Rule; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; -import org.junit.jupiter.migrationsupport.rules.EnableRuleMigrationSupport; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.io.TempDir; import org.slf4j.event.Level; import org.sonar.api.batch.sensor.internal.DefaultSensorDescriptor; import org.sonar.api.batch.sensor.internal.SensorContextTester; @@ -32,18 +31,17 @@ import static org.assertj.core.api.Assertions.assertThat; -@EnableRuleMigrationSupport class DroppedPropertiesSensorTest { - @Rule - public TemporaryFolder tmp = new TemporaryFolder(); + @TempDir + Path tmp; @RegisterExtension public LogTesterJUnit5 logTester = new LogTesterJUnit5().setLevel(Level.DEBUG); @Test void test() throws Exception { - SensorContextTester contextTester = SensorContextTester.create(tmp.newFolder()); + SensorContextTester contextTester = SensorContextTester.create(tmp.toFile()); MapSettings mapSettings = new MapSettings().setProperty("sonar.jacoco.reportPaths", "/path"); contextTester.setSettings(mapSettings); List analysisWarnings = new ArrayList<>(); @@ -57,7 +55,7 @@ void test() throws Exception { @Test void test_two_reportPaths_property() throws Exception { - SensorContextTester contextTester = SensorContextTester.create(tmp.newFolder()); + SensorContextTester contextTester = SensorContextTester.create(tmp.toFile()); MapSettings mapSettings = new MapSettings().setProperty("sonar.jacoco.reportPaths", "/path") .setProperty("sonar.jacoco.reportPath", "/path"); contextTester.setSettings(mapSettings); @@ -71,7 +69,7 @@ void test_two_reportPaths_property() throws Exception { @Test void test_two_reportPaths_property_plus_another() throws Exception { - SensorContextTester contextTester = SensorContextTester.create(tmp.newFolder()); + SensorContextTester contextTester = SensorContextTester.create(tmp.toFile()); MapSettings mapSettings = new MapSettings().setProperty("sonar.jacoco.reportPaths", "/path") .setProperty("sonar.jacoco.reportPath", "/path") .setProperty("sonar.jacoco.itReportPath", "/path"); @@ -87,7 +85,7 @@ void test_two_reportPaths_property_plus_another() throws Exception { @Test void test_empty() throws Exception { - SensorContextTester contextTester = SensorContextTester.create(tmp.newFolder()); + SensorContextTester contextTester = SensorContextTester.create(tmp.toFile()); List analysisWarnings = new ArrayList<>(); DroppedPropertiesSensor sensor = new DroppedPropertiesSensor(analysisWarnings::add); sensor.execute(contextTester); diff --git a/sonar-java-plugin/src/test/java/org/sonar/plugins/java/JavaSensorTest.java b/sonar-java-plugin/src/test/java/org/sonar/plugins/java/JavaSensorTest.java index 76b3573c242..9d6c75c7162 100644 --- a/sonar-java-plugin/src/test/java/org/sonar/plugins/java/JavaSensorTest.java +++ b/sonar-java-plugin/src/test/java/org/sonar/plugins/java/JavaSensorTest.java @@ -24,11 +24,9 @@ import java.util.List; import java.util.Map; import java.util.stream.Stream; -import org.junit.Rule; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; -import org.junit.jupiter.migrationsupport.rules.EnableRuleMigrationSupport; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.io.TempDir; import org.mockito.ArgumentCaptor; import org.slf4j.event.Level; import org.sonar.api.SonarEdition; @@ -90,7 +88,6 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -@EnableRuleMigrationSupport class JavaSensorTest { private static final CheckFactory checkFactory = mock(CheckFactory.class); @@ -102,8 +99,8 @@ class JavaSensorTest { when(checkFactory.create(anyString())).thenReturn(checks); } - @Rule - public final TemporaryFolder tmp = new TemporaryFolder(); + @TempDir + Path tmp; @RegisterExtension public LogTesterJUnit5 logTester = new LogTesterJUnit5().setLevel(Level.DEBUG); @@ -177,7 +174,7 @@ private void testIssueCreation(InputFile.Type onType, int expectedIssues) throws NoSonarFilter noSonarFilter = mock(NoSonarFilter.class); SensorContextTester context = spy(createContext(onType).setRuntime(SonarRuntimeImpl.forSonarLint(Version.create(6, 7)))); DefaultFileSystem fs = context.fileSystem(); - fs.setWorkDir(tmp.newFolder().toPath()); + fs.setWorkDir(Files.createTempDirectory(tmp, "")); SonarComponents sonarComponents = createSonarComponentsMock(context); DefaultJavaResourceLocator javaResourceLocator = createDefaultJavaResourceLocator(settings.asConfig(), fs); @@ -265,14 +262,14 @@ void should_invoke_visitors_on_generated_code_in_batch_mode() throws Exception { } private void assertJasperIsInvoked(MapSettings settings) throws IOException { - Path base = tmp.newFolder().toPath(); - Path generatedFilePath = tmp.newFile("Generated.java").toPath(); + Path base = Files.createTempDirectory(tmp, ""); + Path generatedFilePath = Files.createFile(tmp.resolve("Generated.java")); Files.write(generatedFilePath, "class Generated {}".getBytes()); GeneratedFile generatedFile = new GeneratedFile(generatedFilePath); SensorContextTester context = SensorContextTester.create(base); context.setSettings(settings); - context.fileSystem().setWorkDir(tmp.newFolder().toPath()); + context.fileSystem().setWorkDir(Files.createTempDirectory(tmp, "")); SonarComponents sonarComponents = createSonarComponentsMock(context); JavaFileScanner javaFileScanner = mock(JavaFileScanner.class); JspCodeScanner testCodeVisitor = mock(JspCodeScanner.class); @@ -295,13 +292,13 @@ private void assertJasperIsInvoked(MapSettings settings) throws IOException { @Test void should_not_invoke_jasper_jsp_compilation_in_autoscan_for_security_reasons() throws Exception { - Path base = tmp.newFolder().toPath(); + Path base = Files.createTempDirectory(tmp, ""); MapSettings settings = new MapSettings(); settings.setProperty("sonar.internal.analysis.autoscan", "true"); SensorContextTester context = SensorContextTester.create(base); context.setSettings(settings); - context.fileSystem().setWorkDir(tmp.newFolder().toPath()); + context.fileSystem().setWorkDir(Files.createTempDirectory(tmp, "")); SonarComponents sonarComponents = createSonarComponentsMock(context); JspCodeScanner jspCodeVisitor = mock(JspCodeScanner.class); when(sonarComponents.mainChecks()).thenReturn(Collections.emptyList()); @@ -321,7 +318,7 @@ void should_not_invoke_jasper_jsp_compilation_in_autoscan_for_security_reasons() void performance_measure_should_not_be_activated_by_default() throws IOException { logTester.setLevel(Level.DEBUG); MapSettings settings = new MapSettings(); - Path workDir = tmp.newFolder().toPath(); + Path workDir = Files.createTempDirectory(tmp, ""); executeJavaSensorForPerformanceMeasure(settings, workDir); String debugLogs = String.join("\n", logTester.logs(Level.DEBUG)); assertThat(debugLogs).doesNotContain("Performance Measures:"); @@ -333,7 +330,7 @@ void performance_measure_should_not_be_activated_by_default() throws IOException void performance_measure_should_log_in_debug_mode() throws IOException { MapSettings settings = new MapSettings(); settings.setProperty("sonar.java.performance.measure", "true"); - Path workDir = tmp.newFolder().toPath(); + Path workDir = Files.createTempDirectory(tmp, ""); executeJavaSensorForPerformanceMeasure(settings, workDir); String debugLogs = String.join("\n", logTester.logs(Level.DEBUG)); assertThat(debugLogs).contains("Performance Measures:\n{ \"name\": \"JavaSensor\""); @@ -346,7 +343,7 @@ void performance_measure_should_log_in_debug_mode() throws IOException { void custom_performance_measure_file_path_can_be_provided() throws IOException { logTester.setLevel(Level.DEBUG); MapSettings settings = new MapSettings(); - Path workDir = tmp.newFolder().toPath(); + Path workDir = Files.createTempDirectory(tmp, ""); Path customPerformanceFile = workDir.resolve("custom.performance.measure.json"); settings.setProperty("sonar.java.performance.measure", "true"); settings.setProperty("sonar.java.performance.measure.path", customPerformanceFile.toString()); @@ -365,7 +362,7 @@ void custom_performance_measure_file_path_can_be_empty() throws IOException { MapSettings settings = new MapSettings(); settings.setProperty("sonar.java.performance.measure", "true"); settings.setProperty("sonar.java.performance.measure.path", ""); - Path workDir = tmp.newFolder().toPath(); + Path workDir = Files.createTempDirectory(tmp, ""); executeJavaSensorForPerformanceMeasure(settings, workDir); String debugLogs = String.join("\n", logTester.logs(Level.DEBUG)); assertThat(debugLogs).contains("{ \"name\": \"JavaSensor\""); @@ -379,7 +376,7 @@ void test_java_version_automatically_accepts_enablePreview_flag_when_maximum_ver MapSettings settings = new MapSettings(); settings.setProperty("sonar.java.source", JavaVersionImpl.MAX_SUPPORTED); settings.setProperty("sonar.java.enablePreview", "True"); - Path workDir = tmp.newFolder().toPath(); + Path workDir = Files.createTempDirectory(tmp, ""); executeJavaSensorForPerformanceMeasure(settings, workDir); assertThat(logTester.logs(Level.WARN)).isEmpty(); List infoLogs = logTester.logs(Level.INFO); @@ -393,7 +390,7 @@ void test_java_version_automatically_disables_enablePreview_flag_when_version_is int version = JavaVersionImpl.MAX_SUPPORTED - 1; settings.setProperty("sonar.java.source", version); settings.setProperty("sonar.java.enablePreview", "True"); - Path workDir = tmp.newFolder().toPath(); + Path workDir = Files.createTempDirectory(tmp, ""); executeJavaSensorForPerformanceMeasure(settings, workDir); assertThat(logTester.logs(Level.WARN)).contains( "sonar.java.enablePreview is set but will be discarded as the Java version is less than the max supported version (" + @@ -409,7 +406,7 @@ void getJavaVersion_does_not_try_to_check_consistency_when_sonar_java_source_is_ // We set the sonar.java.enablePreview flag to true but it will be ignored because there is no sonar.java.source MapSettings settings = new MapSettings(); settings.setProperty("sonar.java.enablePreview", "true"); - Path workDir = tmp.newFolder().toPath(); + Path workDir = Files.createTempDirectory(tmp, ""); executeJavaSensorForPerformanceMeasure(settings, workDir); assertThat(logTester.logs(Level.WARN)).noneMatch( log -> log.startsWith("sonar.java.enablePreview is set but will be discarded as the Java version is less than the max supported version") @@ -473,7 +470,7 @@ void custom_file_scanner_is_not_filtered_in_autoscan() throws IOException { .setRuntime(SonarRuntimeImpl.forSonarQube(Version.create(8, 7), SonarQubeSide.SCANNER, SonarEdition.COMMUNITY)); DefaultFileSystem fs = context.fileSystem(); - fs.setWorkDir(tmp.newFolder().toPath()); + fs.setWorkDir(Files.createTempDirectory(tmp, "")); File mainFile = new File(fs.baseDir(), "CodeWithIssues.java"); fs.add(new TestInputFileBuilder("", mainFile.getName()).setLanguage("java").setModuleBaseDir(fs.baseDirPath()) @@ -528,7 +525,7 @@ private SensorContextTester analyzeTwoFilesWithIssues(MapSettings settings) thro .setRuntime(SonarRuntimeImpl.forSonarQube(Version.create(8, 7), SonarQubeSide.SCANNER, SonarEdition.COMMUNITY)); DefaultFileSystem fs = context.fileSystem(); - fs.setWorkDir(tmp.newFolder().toPath()); + fs.setWorkDir(Files.createTempDirectory(tmp, "")); File mainFile = new File(fs.baseDir(), "CodeWithIssues.java"); fs.add(new TestInputFileBuilder("", mainFile.getName()).setLanguage("java").setModuleBaseDir(fs.baseDirPath()) From 31c0c66c75571b6cabc33131cef20aeb5202aec1 Mon Sep 17 00:00:00 2001 From: Daniel Teuchert Date: Thu, 16 Jul 2026 09:22:59 +0200 Subject: [PATCH 2/2] Fix JavaSensorTest type_error_count after removing deprecated imports Removing TemporaryFolder/EnableRuleMigrationSupport imports from JavaSensorTest.java reduced the type error count by 6 (those were unresolvable types). Update the hardcoded expected value from 205 to 199. Co-Authored-By: Claude Sonnet 4.6 (1M context) --- .../src/test/java/org/sonar/plugins/java/JavaSensorTest.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/sonar-java-plugin/src/test/java/org/sonar/plugins/java/JavaSensorTest.java b/sonar-java-plugin/src/test/java/org/sonar/plugins/java/JavaSensorTest.java index 9d6c75c7162..ffdb35d7938 100644 --- a/sonar-java-plugin/src/test/java/org/sonar/plugins/java/JavaSensorTest.java +++ b/sonar-java-plugin/src/test/java/org/sonar/plugins/java/JavaSensorTest.java @@ -132,7 +132,7 @@ void test_issues_creation_on_main_file() throws IOException { "java.scanner_app"); assertThat(telemetryMap.get("java.analysis.main.success.size_chars")).matches("\\d{5}"); assertThat(telemetryMap.get("java.analysis.main.success.time_ms")).matches("\\d+"); - assertThat(telemetryMap).containsEntry("java.analysis.main.success.type_error_count", "205"); + assertThat(telemetryMap).containsEntry("java.analysis.main.success.type_error_count", "199"); } @Test @@ -154,7 +154,7 @@ void test_issues_creation_on_test_file() throws IOException { // NOSONAR require "java.scanner_app"); assertThat(telemetryMap.get("java.analysis.test.success.size_chars")).matches("\\d{5}"); assertThat(telemetryMap.get("java.analysis.test.success.time_ms")).matches("\\d+"); - assertThat(telemetryMap).containsEntry("java.analysis.test.success.type_error_count", "205"); + assertThat(telemetryMap).containsEntry("java.analysis.test.success.type_error_count", "199"); } private static int lineNumberOfTheMethodWithNoSonar(FileSystem fs) throws IOException {