diff --git a/impl/maven-impl/src/test/java/org/apache/maven/impl/AbstractVersionTest.java b/impl/maven-impl/src/test/java/org/apache/maven/impl/AbstractVersionTest.java index f18074ec6003..f430a9795b1b 100644 --- a/impl/maven-impl/src/test/java/org/apache/maven/impl/AbstractVersionTest.java +++ b/impl/maven-impl/src/test/java/org/apache/maven/impl/AbstractVersionTest.java @@ -20,8 +20,7 @@ import org.apache.maven.api.Version; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.assertj.core.api.Assertions.assertThat; /** */ @@ -40,21 +39,21 @@ protected void assertOrder(int expected, String version1, String version2) { Version v2 = newVersion(version2); if (expected > 0) { - assertEquals(1, Integer.signum(v1.compareTo(v2)), "expected " + v1 + " > " + v2); - assertEquals(-1, Integer.signum(v2.compareTo(v1)), "expected " + v2 + " < " + v1); - assertNotEquals(v1, v2, "expected " + v1 + " != " + v2); - assertNotEquals(v2, v1, "expected " + v2 + " != " + v1); + assertThat(Integer.signum(v1.compareTo(v2))).as("expected " + v1 + " > " + v2).isEqualTo(1); + assertThat(Integer.signum(v2.compareTo(v1))).as("expected " + v2 + " < " + v1).isEqualTo(-1); + assertThat(v2).as("expected " + v1 + " != " + v2).isNotEqualTo(v1); + assertThat(v1).as("expected " + v2 + " != " + v1).isNotEqualTo(v2); } else if (expected < 0) { - assertEquals(-1, Integer.signum(v1.compareTo(v2)), "expected " + v1 + " < " + v2); - assertEquals(1, Integer.signum(v2.compareTo(v1)), "expected " + v2 + " > " + v1); - assertNotEquals(v1, v2, "expected " + v1 + " != " + v2); - assertNotEquals(v2, v1, "expected " + v2 + " != " + v1); + assertThat(Integer.signum(v1.compareTo(v2))).as("expected " + v1 + " < " + v2).isEqualTo(-1); + assertThat(Integer.signum(v2.compareTo(v1))).as("expected " + v2 + " > " + v1).isEqualTo(1); + assertThat(v2).as("expected " + v1 + " != " + v2).isNotEqualTo(v1); + assertThat(v1).as("expected " + v2 + " != " + v1).isNotEqualTo(v2); } else { - assertEquals(0, v1.compareTo(v2), "expected " + v1 + " == " + v2); - assertEquals(0, v2.compareTo(v1), "expected " + v2 + " == " + v1); - assertEquals(v1, v2, "expected " + v1 + " == " + v2); - assertEquals(v2, v1, "expected " + v2 + " == " + v1); - assertEquals(v1.hashCode(), v2.hashCode(), "expected #(" + v1 + ") == #(" + v1 + ")"); + assertThat(v1.compareTo(v2)).as("expected " + v1 + " == " + v2).isEqualTo(0); + assertThat(v2.compareTo(v1)).as("expected " + v2 + " == " + v1).isEqualTo(0); + assertThat(v2).as("expected " + v1 + " == " + v2).isEqualTo(v1); + assertThat(v1).as("expected " + v2 + " == " + v1).isEqualTo(v2); + assertThat(v2.hashCode()).as("expected #(" + v1 + ") == #(" + v1 + ")").isEqualTo(v1.hashCode()); } } diff --git a/impl/maven-impl/src/test/java/org/apache/maven/impl/DefaultModelVersionParserTest.java b/impl/maven-impl/src/test/java/org/apache/maven/impl/DefaultModelVersionParserTest.java index 9bceb1926a16..1d55d37d1b30 100644 --- a/impl/maven-impl/src/test/java/org/apache/maven/impl/DefaultModelVersionParserTest.java +++ b/impl/maven-impl/src/test/java/org/apache/maven/impl/DefaultModelVersionParserTest.java @@ -22,15 +22,14 @@ import org.eclipse.aether.util.version.GenericVersionScheme; import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; class DefaultModelVersionParserTest { @Test void parseVersion() { Version v = new DefaultModelVersionParser(new GenericVersionScheme()).parseVersion(""); - assertNotNull(v); - assertEquals("", v.toString()); + assertThat(v).isNotNull(); + assertThat(v.toString()).isEqualTo(""); } } diff --git a/impl/maven-impl/src/test/java/org/apache/maven/impl/DefaultModelXmlFactoryTest.java b/impl/maven-impl/src/test/java/org/apache/maven/impl/DefaultModelXmlFactoryTest.java index f10d46fdd852..32d6b2d88cd2 100644 --- a/impl/maven-impl/src/test/java/org/apache/maven/impl/DefaultModelXmlFactoryTest.java +++ b/impl/maven-impl/src/test/java/org/apache/maven/impl/DefaultModelXmlFactoryTest.java @@ -26,9 +26,8 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType; class DefaultModelXmlFactoryTest { @@ -40,7 +39,7 @@ void setUp() { } @Test - void testValidNamespaceWithModelVersion400() throws Exception { + void validNamespaceWithModelVersion400() throws Exception { String xml = """ @@ -51,12 +50,12 @@ void testValidNamespaceWithModelVersion400() throws Exception { XmlReaderRequest.builder().reader(new StringReader(xml)).build(); Model model = factory.read(request); - assertEquals("4.0.0", model.getModelVersion()); - assertEquals("http://maven.apache.org/POM/4.0.0", model.getNamespaceUri()); + assertThat(model.getModelVersion()).isEqualTo("4.0.0"); + assertThat(model.getNamespaceUri()).isEqualTo("http://maven.apache.org/POM/4.0.0"); } @Test - void testValidNamespaceWithModelVersion410() throws Exception { + void validNamespaceWithModelVersion410() throws Exception { String xml = """ @@ -67,12 +66,12 @@ void testValidNamespaceWithModelVersion410() throws Exception { XmlReaderRequest.builder().reader(new StringReader(xml)).build(); Model model = factory.read(request); - assertEquals("4.1.0", model.getModelVersion()); - assertEquals("http://maven.apache.org/POM/4.1.0", model.getNamespaceUri()); + assertThat(model.getModelVersion()).isEqualTo("4.1.0"); + assertThat(model.getNamespaceUri()).isEqualTo("http://maven.apache.org/POM/4.1.0"); } @Test - void testInvalidNamespaceWithModelVersion410() { + void invalidNamespaceWithModelVersion410() { String xml = """ @@ -82,13 +81,13 @@ void testInvalidNamespaceWithModelVersion410() { XmlReaderRequest request = XmlReaderRequest.builder().reader(new StringReader(xml)).build(); - XmlReaderException ex = assertThrows(XmlReaderException.class, () -> factory.read(request)); - assertTrue(ex.getMessage().contains("Invalid namespace 'http://invalid.namespace/4.1.0'")); - assertTrue(ex.getMessage().contains("4.1.0")); + XmlReaderException ex = assertThatExceptionOfType(XmlReaderException.class).isThrownBy(() -> factory.read(request)).actual(); + assertThat(ex.getMessage().contains("Invalid namespace 'http://invalid.namespace/4.1.0'")).isTrue(); + assertThat(ex.getMessage().contains("4.1.0")).isTrue(); } @Test - void testNoNamespaceWithModelVersion400() throws Exception { + void noNamespaceWithModelVersion400() throws Exception { String xml = """ @@ -99,17 +98,17 @@ void testNoNamespaceWithModelVersion400() throws Exception { XmlReaderRequest.builder().reader(new StringReader(xml)).build(); Model model = factory.read(request); - assertEquals("4.0.0", model.getModelVersion()); - assertEquals("", model.getNamespaceUri()); + assertThat(model.getModelVersion()).isEqualTo("4.0.0"); + assertThat(model.getNamespaceUri()).isEqualTo(""); } @Test - void testNullRequest() { - assertThrows(IllegalArgumentException.class, () -> factory.read((XmlReaderRequest) null)); + void nullRequest() { + assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> factory.read((XmlReaderRequest) null)); } @Test - void testMalformedModelVersion() throws Exception { + void malformedModelVersion() throws Exception { String xml = """ @@ -120,6 +119,6 @@ void testMalformedModelVersion() throws Exception { XmlReaderRequest.builder().reader(new StringReader(xml)).build(); Model model = factory.read(request); - assertEquals("invalid.version", model.getModelVersion()); + assertThat(model.getModelVersion()).isEqualTo("invalid.version"); } } diff --git a/impl/maven-impl/src/test/java/org/apache/maven/impl/DefaultNodeTest.java b/impl/maven-impl/src/test/java/org/apache/maven/impl/DefaultNodeTest.java index a67fd4727192..89e9ec2f37e6 100644 --- a/impl/maven-impl/src/test/java/org/apache/maven/impl/DefaultNodeTest.java +++ b/impl/maven-impl/src/test/java/org/apache/maven/impl/DefaultNodeTest.java @@ -27,12 +27,12 @@ import org.junit.jupiter.api.Test; import org.mockito.Mockito; -import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; class DefaultNodeTest { @Test - void testAsString() { + void asString() { InternalSession session = Mockito.mock(InternalSession.class); // Create a basic dependency node @@ -42,21 +42,19 @@ void testAsString() { // Test non-verbose mode DefaultNode defaultNode = new DefaultNode(session, node, false); - assertEquals("org.example:myapp:jar:1.0:compile", defaultNode.asString()); + assertThat(defaultNode.asString()).isEqualTo("org.example:myapp:jar:1.0:compile"); // Test verbose mode with managed version node.setData(DependencyManagerUtils.NODE_DATA_PREMANAGED_VERSION, "0.9"); node.setManagedBits(DependencyNode.MANAGED_VERSION); defaultNode = new DefaultNode(session, node, true); - assertEquals("org.example:myapp:jar:1.0:compile (version managed from 0.9)", defaultNode.asString()); + assertThat(defaultNode.asString()).isEqualTo("org.example:myapp:jar:1.0:compile (version managed from 0.9)"); // Test verbose mode with managed scope node.setData(DependencyManagerUtils.NODE_DATA_PREMANAGED_SCOPE, "runtime"); node.setManagedBits(DependencyNode.MANAGED_VERSION | DependencyNode.MANAGED_SCOPE); defaultNode = new DefaultNode(session, node, true); - assertEquals( - "org.example:myapp:jar:1.0:compile (version managed from 0.9; scope managed from runtime)", - defaultNode.asString()); + assertThat(defaultNode.asString()).isEqualTo("org.example:myapp:jar:1.0:compile (version managed from 0.9; scope managed from runtime)"); // Test verbose mode with conflict resolution DefaultDependencyNode winner = @@ -64,6 +62,6 @@ void testAsString() { node.setData(ConflictResolver.NODE_DATA_WINNER, winner); node.setManagedBits(0); defaultNode = new DefaultNode(session, node, true); - assertEquals("(org.example:myapp:jar:1.0:compile - omitted for conflict with 2.0)", defaultNode.asString()); + assertThat(defaultNode.asString()).isEqualTo("(org.example:myapp:jar:1.0:compile - omitted for conflict with 2.0)"); } } diff --git a/impl/maven-impl/src/test/java/org/apache/maven/impl/DefaultProblemCollectorTest.java b/impl/maven-impl/src/test/java/org/apache/maven/impl/DefaultProblemCollectorTest.java index b6623e033772..966c62e308ed 100644 --- a/impl/maven-impl/src/test/java/org/apache/maven/impl/DefaultProblemCollectorTest.java +++ b/impl/maven-impl/src/test/java/org/apache/maven/impl/DefaultProblemCollectorTest.java @@ -24,9 +24,7 @@ import org.apache.maven.api.services.ProblemCollector; import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * This UT is for {@link ProblemCollector} but here we have implementations for problems. @@ -36,51 +34,51 @@ class DefaultProblemCollectorTest { void severityFatalDetection() { ProblemCollector collector = ProblemCollector.create(5); - assertFalse(collector.hasProblemsFor(BuilderProblem.Severity.WARNING)); - assertFalse(collector.hasErrorProblems()); - assertFalse(collector.hasFatalProblems()); + assertThat(collector.hasProblemsFor(BuilderProblem.Severity.WARNING)).isFalse(); + assertThat(collector.hasErrorProblems()).isFalse(); + assertThat(collector.hasFatalProblems()).isFalse(); collector.reportProblem( new DefaultBuilderProblem("source", 0, 0, null, "message", BuilderProblem.Severity.FATAL)); // fatal triggers all - assertTrue(collector.hasProblemsFor(BuilderProblem.Severity.WARNING)); - assertTrue(collector.hasErrorProblems()); - assertTrue(collector.hasFatalProblems()); + assertThat(collector.hasProblemsFor(BuilderProblem.Severity.WARNING)).isTrue(); + assertThat(collector.hasErrorProblems()).isTrue(); + assertThat(collector.hasFatalProblems()).isTrue(); } @Test void severityErrorDetection() { ProblemCollector collector = ProblemCollector.create(5); - assertFalse(collector.hasProblemsFor(BuilderProblem.Severity.WARNING)); - assertFalse(collector.hasErrorProblems()); - assertFalse(collector.hasFatalProblems()); + assertThat(collector.hasProblemsFor(BuilderProblem.Severity.WARNING)).isFalse(); + assertThat(collector.hasErrorProblems()).isFalse(); + assertThat(collector.hasFatalProblems()).isFalse(); collector.reportProblem( new DefaultBuilderProblem("source", 0, 0, null, "message", BuilderProblem.Severity.ERROR)); // error triggers error + warning - assertTrue(collector.hasProblemsFor(BuilderProblem.Severity.WARNING)); - assertTrue(collector.hasErrorProblems()); - assertFalse(collector.hasFatalProblems()); + assertThat(collector.hasProblemsFor(BuilderProblem.Severity.WARNING)).isTrue(); + assertThat(collector.hasErrorProblems()).isTrue(); + assertThat(collector.hasFatalProblems()).isFalse(); } @Test void severityWarningDetection() { ProblemCollector collector = ProblemCollector.create(5); - assertFalse(collector.hasProblemsFor(BuilderProblem.Severity.WARNING)); - assertFalse(collector.hasErrorProblems()); - assertFalse(collector.hasFatalProblems()); + assertThat(collector.hasProblemsFor(BuilderProblem.Severity.WARNING)).isFalse(); + assertThat(collector.hasErrorProblems()).isFalse(); + assertThat(collector.hasFatalProblems()).isFalse(); collector.reportProblem( new DefaultBuilderProblem("source", 0, 0, null, "message", BuilderProblem.Severity.WARNING)); // warning triggers warning only - assertTrue(collector.hasProblemsFor(BuilderProblem.Severity.WARNING)); - assertFalse(collector.hasErrorProblems()); - assertFalse(collector.hasFatalProblems()); + assertThat(collector.hasProblemsFor(BuilderProblem.Severity.WARNING)).isTrue(); + assertThat(collector.hasErrorProblems()).isFalse(); + assertThat(collector.hasFatalProblems()).isFalse(); } @Test @@ -91,18 +89,18 @@ void lossy() { "source", 0, 0, null, "message " + i, BuilderProblem.Severity.WARNING))); // collector is "full" of warnings - assertFalse(collector.reportProblem( - new DefaultBuilderProblem("source", 0, 0, null, "message", BuilderProblem.Severity.WARNING))); + assertThat(collector.reportProblem( + new DefaultBuilderProblem("source", 0, 0, null, "message", BuilderProblem.Severity.WARNING))).isFalse(); // but collector will drop warning for more severe issues - assertTrue(collector.reportProblem( - new DefaultBuilderProblem("source", 0, 0, null, "message", BuilderProblem.Severity.ERROR))); - assertTrue(collector.reportProblem( - new DefaultBuilderProblem("source", 0, 0, null, "message", BuilderProblem.Severity.FATAL))); + assertThat(collector.reportProblem( + new DefaultBuilderProblem("source", 0, 0, null, "message", BuilderProblem.Severity.ERROR))).isTrue(); + assertThat(collector.reportProblem( + new DefaultBuilderProblem("source", 0, 0, null, "message", BuilderProblem.Severity.FATAL))).isTrue(); // collector is full of warnings, errors and fatal (mixed) - assertFalse(collector.reportProblem( - new DefaultBuilderProblem("source", 0, 0, null, "message", BuilderProblem.Severity.WARNING))); + assertThat(collector.reportProblem( + new DefaultBuilderProblem("source", 0, 0, null, "message", BuilderProblem.Severity.WARNING))).isFalse(); // fill it up with fatal ones IntStream.range(0, 5) @@ -110,53 +108,53 @@ void lossy() { "source", 0, 0, null, "message " + i, BuilderProblem.Severity.FATAL))); // from now on, only counters work, problems are lost - assertFalse(collector.reportProblem( - new DefaultBuilderProblem("source", 0, 0, null, "message", BuilderProblem.Severity.WARNING))); - assertFalse(collector.reportProblem( - new DefaultBuilderProblem("source", 0, 0, null, "message", BuilderProblem.Severity.ERROR))); - assertFalse(collector.reportProblem( - new DefaultBuilderProblem("source", 0, 0, null, "message", BuilderProblem.Severity.FATAL))); - - assertEquals(17, collector.totalProblemsReported()); - assertEquals(8, collector.problemsReportedFor(BuilderProblem.Severity.WARNING)); - assertEquals(2, collector.problemsReportedFor(BuilderProblem.Severity.ERROR)); - assertEquals(7, collector.problemsReportedFor(BuilderProblem.Severity.FATAL)); + assertThat(collector.reportProblem( + new DefaultBuilderProblem("source", 0, 0, null, "message", BuilderProblem.Severity.WARNING))).isFalse(); + assertThat(collector.reportProblem( + new DefaultBuilderProblem("source", 0, 0, null, "message", BuilderProblem.Severity.ERROR))).isFalse(); + assertThat(collector.reportProblem( + new DefaultBuilderProblem("source", 0, 0, null, "message", BuilderProblem.Severity.FATAL))).isFalse(); + + assertThat(collector.totalProblemsReported()).isEqualTo(17); + assertThat(collector.problemsReportedFor(BuilderProblem.Severity.WARNING)).isEqualTo(8); + assertThat(collector.problemsReportedFor(BuilderProblem.Severity.ERROR)).isEqualTo(2); + assertThat(collector.problemsReportedFor(BuilderProblem.Severity.FATAL)).isEqualTo(7); // but preserved problems count == capacity - assertEquals(5, collector.problems().count()); + assertThat(collector.problems().count()).isEqualTo(5); } @Test void moreSeverePushOutLeastSevere() { ProblemCollector collector = ProblemCollector.create(5); - assertEquals(0, collector.totalProblemsReported()); - assertEquals(0, collector.problems().count()); + assertThat(collector.totalProblemsReported()).isEqualTo(0); + assertThat(collector.problems().count()).isEqualTo(0); IntStream.range(0, 5) .forEach(i -> collector.reportProblem(new DefaultBuilderProblem( "source", 0, 0, null, "message " + i, BuilderProblem.Severity.WARNING))); - assertEquals(5, collector.totalProblemsReported()); - assertEquals(5, collector.problems().count()); + assertThat(collector.totalProblemsReported()).isEqualTo(5); + assertThat(collector.problems().count()).isEqualTo(5); IntStream.range(0, 5) .forEach(i -> collector.reportProblem(new DefaultBuilderProblem( "source", 0, 0, null, "message " + i, BuilderProblem.Severity.ERROR))); - assertEquals(10, collector.totalProblemsReported()); - assertEquals(5, collector.problems().count()); + assertThat(collector.totalProblemsReported()).isEqualTo(10); + assertThat(collector.problems().count()).isEqualTo(5); IntStream.range(0, 4) .forEach(i -> collector.reportProblem(new DefaultBuilderProblem( "source", 0, 0, null, "message " + i, BuilderProblem.Severity.FATAL))); - assertEquals(14, collector.totalProblemsReported()); - assertEquals(5, collector.problems().count()); + assertThat(collector.totalProblemsReported()).isEqualTo(14); + assertThat(collector.problems().count()).isEqualTo(5); - assertEquals(5, collector.problemsReportedFor(BuilderProblem.Severity.WARNING)); - assertEquals(5, collector.problemsReportedFor(BuilderProblem.Severity.ERROR)); - assertEquals(4, collector.problemsReportedFor(BuilderProblem.Severity.FATAL)); + assertThat(collector.problemsReportedFor(BuilderProblem.Severity.WARNING)).isEqualTo(5); + assertThat(collector.problemsReportedFor(BuilderProblem.Severity.ERROR)).isEqualTo(5); + assertThat(collector.problemsReportedFor(BuilderProblem.Severity.FATAL)).isEqualTo(4); - assertEquals(0, collector.problems(BuilderProblem.Severity.WARNING).count()); - assertEquals(1, collector.problems(BuilderProblem.Severity.ERROR).count()); - assertEquals(4, collector.problems(BuilderProblem.Severity.FATAL).count()); + assertThat(collector.problems(BuilderProblem.Severity.WARNING).count()).isEqualTo(0); + assertThat(collector.problems(BuilderProblem.Severity.ERROR).count()).isEqualTo(1); + assertThat(collector.problems(BuilderProblem.Severity.FATAL).count()).isEqualTo(4); } } diff --git a/impl/maven-impl/src/test/java/org/apache/maven/impl/DefaultSettingsBuilderFactoryTest.java b/impl/maven-impl/src/test/java/org/apache/maven/impl/DefaultSettingsBuilderFactoryTest.java index 5419b27d6287..4bea8e37d706 100644 --- a/impl/maven-impl/src/test/java/org/apache/maven/impl/DefaultSettingsBuilderFactoryTest.java +++ b/impl/maven-impl/src/test/java/org/apache/maven/impl/DefaultSettingsBuilderFactoryTest.java @@ -36,7 +36,7 @@ import org.mockito.Mockito; import org.mockito.junit.jupiter.MockitoExtension; -import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; /** */ @@ -54,10 +54,10 @@ void setup() { } @Test - void testCompleteWiring() { + void completeWiring() { SettingsBuilder builder = new DefaultSettingsBuilder(new DefaultSettingsXmlFactory(), new DefaultInterpolator(), Map.of()); - assertNotNull(builder); + assertThat(builder).isNotNull(); SettingsBuilderRequest request = SettingsBuilderRequest.builder() .session(session) @@ -65,8 +65,8 @@ void testCompleteWiring() { .build(); SettingsBuilderResult result = builder.build(request); - assertNotNull(result); - assertNotNull(result.getEffectiveSettings()); + assertThat(result).isNotNull(); + assertThat(result.getEffectiveSettings()).isNotNull(); } private Path getSettings(String name) { diff --git a/impl/maven-impl/src/test/java/org/apache/maven/impl/DefaultSettingsValidatorTest.java b/impl/maven-impl/src/test/java/org/apache/maven/impl/DefaultSettingsValidatorTest.java index f604fe6bb3af..53ae98f2b4a7 100644 --- a/impl/maven-impl/src/test/java/org/apache/maven/impl/DefaultSettingsValidatorTest.java +++ b/impl/maven-impl/src/test/java/org/apache/maven/impl/DefaultSettingsValidatorTest.java @@ -31,7 +31,7 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; class DefaultSettingsValidatorTest { @@ -43,31 +43,31 @@ void setUp() throws Exception { } @Test - void testValidate() { + void validate() { Profile prof = Profile.newBuilder().id("xxx").build(); Settings model = Settings.newBuilder().profiles(List.of(prof)).build(); ProblemCollector problems = validator.validate(model); - assertEquals(0, problems.totalProblemsReported()); + assertThat(problems.totalProblemsReported()).isEqualTo(0); Repository repo = org.apache.maven.api.settings.Repository.newInstance(false); Settings model2 = Settings.newBuilder() .profiles(List.of(prof.withRepositories(List.of(repo)))) .build(); problems = validator.validate(model2); - assertEquals(2, problems.totalProblemsReported()); + assertThat(problems.totalProblemsReported()).isEqualTo(2); repo = repo.withUrl("http://xxx.xxx.com"); model2 = Settings.newBuilder() .profiles(List.of(prof.withRepositories(List.of(repo)))) .build(); problems = validator.validate(model2); - assertEquals(1, problems.totalProblemsReported()); + assertThat(problems.totalProblemsReported()).isEqualTo(1); repo = repo.withId("xxx"); model2 = Settings.newBuilder() .profiles(List.of(prof.withRepositories(List.of(repo)))) .build(); problems = validator.validate(model2); - assertEquals(0, problems.totalProblemsReported()); + assertThat(problems.totalProblemsReported()).isEqualTo(0); } } diff --git a/impl/maven-impl/src/test/java/org/apache/maven/impl/DefaultToolchainManagerTest.java b/impl/maven-impl/src/test/java/org/apache/maven/impl/DefaultToolchainManagerTest.java index c916d0ca5fcc..d1859b336f7b 100644 --- a/impl/maven-impl/src/test/java/org/apache/maven/impl/DefaultToolchainManagerTest.java +++ b/impl/maven-impl/src/test/java/org/apache/maven/impl/DefaultToolchainManagerTest.java @@ -36,9 +36,8 @@ import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -80,14 +79,14 @@ void getToolchainsWithValidTypeAndRequirements() { List result = manager.getToolchains(session, "jdk", Map.of("version", "11")); - assertEquals(1, result.size()); - assertEquals(mockToolchain, result.get(0)); + assertThat(result.size()).isEqualTo(1); + assertThat(result.get(0)).isEqualTo(mockToolchain); } @Test void getToolchainsWithInvalidType() { List result = manager.getToolchains(session, "invalid", null); - assertTrue(result.isEmpty()); + assertThat(result.isEmpty()).isTrue(); } @Test @@ -106,8 +105,8 @@ void storeAndRetrieveToolchainFromBuildContext() { manager.storeToolchainToBuildContext(session, mockToolchain); Optional result = manager.getToolchainFromBuildContext(session, "jdk"); - assertTrue(result.isPresent()); - assertEquals(mockToolchain, result.get()); + assertThat(result.isPresent()).isTrue(); + assertThat(result.get()).isEqualTo(mockToolchain); } @Test @@ -115,11 +114,11 @@ void retrieveContextWithoutProject() { when(session.getService(Lookup.class)).thenReturn(lookup); when(lookup.lookupOptional(Project.class)).thenReturn(Optional.empty()); - assertTrue(manager.retrieveContext(session).isEmpty()); + assertThat(manager.retrieveContext(session).isEmpty()).isTrue(); } @Test void getToolchainsWithNullType() { - assertThrows(NullPointerException.class, () -> manager.getToolchains(session, null, null)); + assertThatExceptionOfType(NullPointerException.class).isThrownBy(() -> manager.getToolchains(session, null, null)); } } diff --git a/impl/maven-impl/src/test/java/org/apache/maven/impl/ModelVersionParserTest.java b/impl/maven-impl/src/test/java/org/apache/maven/impl/ModelVersionParserTest.java index 6feffa0ae76f..23325d3e9822 100644 --- a/impl/maven-impl/src/test/java/org/apache/maven/impl/ModelVersionParserTest.java +++ b/impl/maven-impl/src/test/java/org/apache/maven/impl/ModelVersionParserTest.java @@ -23,13 +23,10 @@ import org.eclipse.aether.util.version.GenericVersionScheme; import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.junit.jupiter.api.Assertions.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; -public class ModelVersionParserTest { +class ModelVersionParserTest { private final DefaultModelVersionParser versionParser = new DefaultModelVersionParser(new GenericVersionScheme()); @@ -38,23 +35,23 @@ private void parseInvalid(String constraint) { versionParser.parseVersionConstraint(constraint); fail("expected exception for constraint " + constraint); } catch (VersionParserException e) { - assertNotNull(e.getMessage()); + assertThat(e.getMessage()).isNotNull(); } } @Test - void testEnumeratedVersions() throws VersionParserException { + void enumeratedVersions() throws VersionParserException { VersionConstraint c = versionParser.parseVersionConstraint("1.0"); - assertEquals("1.0", c.getRecommendedVersion().toString()); - assertTrue(c.contains(versionParser.parseVersion("1.0"))); + assertThat(c.getRecommendedVersion().toString()).isEqualTo("1.0"); + assertThat(c.contains(versionParser.parseVersion("1.0"))).isTrue(); c = versionParser.parseVersionConstraint("[1.0]"); - assertNull(c.getRecommendedVersion()); - assertTrue(c.contains(versionParser.parseVersion("1.0"))); + assertThat(c.getRecommendedVersion()).isNull(); + assertThat(c.contains(versionParser.parseVersion("1.0"))).isTrue(); c = versionParser.parseVersionConstraint("[1.0],[2.0]"); - assertTrue(c.contains(versionParser.parseVersion("1.0"))); - assertTrue(c.contains(versionParser.parseVersion("2.0"))); + assertThat(c.contains(versionParser.parseVersion("1.0"))).isTrue(); + assertThat(c.contains(versionParser.parseVersion("2.0"))).isTrue(); c = versionParser.parseVersionConstraint("[1.0],[2.0],[3.0]"); assertContains(c, "1.0", "2.0", "3.0"); @@ -75,7 +72,7 @@ private void assertNotContains(VersionConstraint c, String... versions) { private void assertContains(String msg, VersionConstraint c, boolean b, String... versions) { for (String v : versions) { - assertEquals(b, c.contains(versionParser.parseVersion(v)), String.format(msg, v)); + assertThat(c.contains(versionParser.parseVersion(v))).as(String.format(msg, v)).isEqualTo(b); } } @@ -84,18 +81,18 @@ private void assertContains(VersionConstraint c, String... versions) { } @Test - void testInvalid() { + void invalid() { parseInvalid("[1,"); parseInvalid("[1,2],(3,"); parseInvalid("[1,2],3"); } @Test - void testSameUpperAndLowerBound() throws VersionParserException { + void sameUpperAndLowerBound() throws VersionParserException { VersionConstraint c = versionParser.parseVersionConstraint("[1.0]"); - assertEquals("[1.0,1.0]", c.toString()); + assertThat(c.toString()).isEqualTo("[1.0,1.0]"); VersionConstraint c2 = versionParser.parseVersionConstraint(c.toString()); - assertEquals(c, c2); - assertTrue(c.contains(versionParser.parseVersion("1.0"))); + assertThat(c2).isEqualTo(c); + assertThat(c.contains(versionParser.parseVersion("1.0"))).isTrue(); } } diff --git a/impl/maven-impl/src/test/java/org/apache/maven/impl/RequestTraceHelperTest.java b/impl/maven-impl/src/test/java/org/apache/maven/impl/RequestTraceHelperTest.java index 33294298ad1f..1ee4397b7984 100644 --- a/impl/maven-impl/src/test/java/org/apache/maven/impl/RequestTraceHelperTest.java +++ b/impl/maven-impl/src/test/java/org/apache/maven/impl/RequestTraceHelperTest.java @@ -23,10 +23,7 @@ import org.eclipse.aether.resolution.ArtifactRequest; import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @@ -34,7 +31,7 @@ class RequestTraceHelperTest { @Test - void testEnterWithRequestData() { + void enterWithRequestData() { InternalSession session = mock(InternalSession.class); Request request = mock(Request.class); org.apache.maven.api.services.RequestTrace existingTrace = @@ -44,33 +41,33 @@ void testEnterWithRequestData() { RequestTraceHelper.ResolverTrace result = RequestTraceHelper.enter(session, request); - assertNotNull(result); - assertEquals(existingTrace, result.mvnTrace()); + assertThat(result).isNotNull(); + assertThat(result.mvnTrace()).isEqualTo(existingTrace); verify(session).setCurrentTrace(existingTrace); } @Test - void testInterpretTraceWithArtifactRequest() { + void interpretTraceWithArtifactRequest() { ArtifactRequest artifactRequest = mock(ArtifactRequest.class); RequestTrace trace = RequestTrace.newChild(null, artifactRequest); String result = RequestTraceHelper.interpretTrace(false, trace); - assertTrue(result.startsWith("artifact request for ")); + assertThat(result.startsWith("artifact request for ")).isTrue(); } @Test - void testToMavenWithNullTrace() { - assertNull(RequestTraceHelper.toMaven("test", null)); + void toMavenWithNullTrace() { + assertThat(RequestTraceHelper.toMaven("test", null)).isNull(); } @Test - void testToResolverWithNullTrace() { - assertNull(RequestTraceHelper.toResolver(null)); + void toResolverWithNullTrace() { + assertThat(RequestTraceHelper.toResolver(null)).isNull(); } @Test - void testExitResetsParentTrace() { + void exitResetsParentTrace() { InternalSession session = mock(InternalSession.class); org.apache.maven.api.services.RequestTrace parentTrace = new org.apache.maven.api.services.RequestTrace(null, "parent"); diff --git a/impl/maven-impl/src/test/java/org/apache/maven/impl/VersionRangeTest.java b/impl/maven-impl/src/test/java/org/apache/maven/impl/VersionRangeTest.java index 9e1b74ff3edc..94c63defdd75 100644 --- a/impl/maven-impl/src/test/java/org/apache/maven/impl/VersionRangeTest.java +++ b/impl/maven-impl/src/test/java/org/apache/maven/impl/VersionRangeTest.java @@ -25,12 +25,10 @@ import org.eclipse.aether.util.version.GenericVersionScheme; import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.junit.jupiter.api.Assertions.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; -public class VersionRangeTest { +class VersionRangeTest { private ModelVersionParser versionParser = new DefaultModelVersionParser(new GenericVersionScheme()); @@ -51,93 +49,93 @@ private void parseInvalid(String range) { versionParser.parseVersionRange(range); fail(range + " should be invalid"); } catch (VersionParserException e) { - assertTrue(true); + assertThat(true).isTrue(); } } private void assertContains(VersionRange range, String version) { - assertTrue(range.contains(newVersion(version)), range + " should contain " + version); + assertThat(range.contains(newVersion(version))).as(range + " should contain " + version).isTrue(); } private void assertNotContains(VersionRange range, String version) { - assertFalse(range.contains(newVersion(version)), range + " should not contain " + version); + assertThat(range.contains(newVersion(version))).as(range + " should not contain " + version).isFalse(); } @Test - void testLowerBoundInclusiveUpperBoundInclusive() { + void lowerBoundInclusiveUpperBoundInclusive() { VersionRange range = parseValid("[1,2]"); assertContains(range, "1"); assertContains(range, "1.1-SNAPSHOT"); assertContains(range, "2"); - assertEquals(range, parseValid(range.toString())); + assertThat(parseValid(range.toString())).isEqualTo(range); } @Test - void testLowerBoundInclusiveUpperBoundExclusive() { + void lowerBoundInclusiveUpperBoundExclusive() { VersionRange range = parseValid("[1.2.3.4.5,1.2.3.4.6)"); assertContains(range, "1.2.3.4.5"); assertNotContains(range, "1.2.3.4.6"); - assertEquals(range, parseValid(range.toString())); + assertThat(parseValid(range.toString())).isEqualTo(range); } @Test - void testLowerBoundExclusiveUpperBoundInclusive() { + void lowerBoundExclusiveUpperBoundInclusive() { VersionRange range = parseValid("(1a,1b]"); assertNotContains(range, "1a"); assertContains(range, "1b"); - assertEquals(range, parseValid(range.toString())); + assertThat(parseValid(range.toString())).isEqualTo(range); } @Test - void testLowerBoundExclusiveUpperBoundExclusive() { + void lowerBoundExclusiveUpperBoundExclusive() { VersionRange range = parseValid("(1,3)"); assertNotContains(range, "1"); assertContains(range, "2-SNAPSHOT"); assertNotContains(range, "3"); - assertEquals(range, parseValid(range.toString())); + assertThat(parseValid(range.toString())).isEqualTo(range); } @Test - void testSingleVersion() { + void singleVersion() { VersionRange range = parseValid("[1]"); assertContains(range, "1"); - assertEquals(range, parseValid(range.toString())); + assertThat(parseValid(range.toString())).isEqualTo(range); range = parseValid("[1,1]"); assertContains(range, "1"); - assertEquals(range, parseValid(range.toString())); + assertThat(parseValid(range.toString())).isEqualTo(range); } @Test - void testSingleWildcardVersion() { + void singleWildcardVersion() { VersionRange range = parseValid("[1.2.*]"); assertContains(range, "1.2-alpha-1"); assertContains(range, "1.2-SNAPSHOT"); assertContains(range, "1.2"); assertContains(range, "1.2.9999999"); assertNotContains(range, "1.3-rc-1"); - assertEquals(range, parseValid(range.toString())); + assertThat(parseValid(range.toString())).isEqualTo(range); } @Test - void testMissingOpenCloseDelimiter() { + void missingOpenCloseDelimiter() { parseInvalid("1.0"); } @Test - void testMissingOpenDelimiter() { + void missingOpenDelimiter() { parseInvalid("1.0]"); parseInvalid("1.0)"); } @Test - void testMissingCloseDelimiter() { + void missingCloseDelimiter() { parseInvalid("[1.0"); parseInvalid("(1.0"); } @Test - void testTooManyVersions() { + void tooManyVersions() { parseInvalid("[1,2,3]"); parseInvalid("(1,2,3)"); parseInvalid("[1,2,3)"); diff --git a/impl/maven-impl/src/test/java/org/apache/maven/impl/VersionTest.java b/impl/maven-impl/src/test/java/org/apache/maven/impl/VersionTest.java index 27ad33272838..5a16965578b7 100644 --- a/impl/maven-impl/src/test/java/org/apache/maven/impl/VersionTest.java +++ b/impl/maven-impl/src/test/java/org/apache/maven/impl/VersionTest.java @@ -30,11 +30,11 @@ import org.eclipse.aether.util.version.GenericVersionScheme; import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.fail; +import static org.assertj.core.api.Assertions.fail; /** */ -public class VersionTest extends AbstractVersionTest { +class VersionTest extends AbstractVersionTest { private final ModelVersionParser modelVersionParser = new DefaultModelVersionParser(new GenericVersionScheme()); protected Version newVersion(String version) { @@ -42,12 +42,12 @@ protected Version newVersion(String version) { } @Test - void testEmptyVersion() { + void emptyVersion() { assertOrder(AbstractVersionTest.X_EQ_Y, "0", ""); } @Test - void testNumericOrdering() { + void numericOrdering() { assertOrder(AbstractVersionTest.X_LT_Y, "2", "10"); assertOrder(AbstractVersionTest.X_LT_Y, "1.2", "1.10"); assertOrder(AbstractVersionTest.X_LT_Y, "1.0.2", "1.0.10"); @@ -57,14 +57,14 @@ void testNumericOrdering() { } @Test - void testDelimiters() { + void delimiters() { assertOrder(AbstractVersionTest.X_EQ_Y, "1.0", "1-0"); assertOrder(AbstractVersionTest.X_EQ_Y, "1.0", "1_0"); assertOrder(AbstractVersionTest.X_EQ_Y, "1.a", "1a"); } @Test - void testLeadingZerosAreSemanticallyIrrelevant() { + void leadingZerosAreSemanticallyIrrelevant() { assertOrder(AbstractVersionTest.X_EQ_Y, "1", "01"); assertOrder(AbstractVersionTest.X_EQ_Y, "1.2", "1.002"); assertOrder(AbstractVersionTest.X_EQ_Y, "1.2.3", "1.2.0003"); @@ -72,7 +72,7 @@ void testLeadingZerosAreSemanticallyIrrelevant() { } @Test - void testTrailingZerosAreSemanticallyIrrelevant() { + void trailingZerosAreSemanticallyIrrelevant() { assertOrder(AbstractVersionTest.X_EQ_Y, "1", "1.0.0.0.0.0.0.0.0.0.0.0.0.0"); assertOrder(AbstractVersionTest.X_EQ_Y, "1", "1-0-0-0-0-0-0-0-0-0-0-0-0-0"); assertOrder(AbstractVersionTest.X_EQ_Y, "1", "1.0-0.0-0.0-0.0-0.0-0.0-0.0"); @@ -81,7 +81,7 @@ void testTrailingZerosAreSemanticallyIrrelevant() { } @Test - void testTrailingZerosBeforeQualifierAreSemanticallyIrrelevant() { + void trailingZerosBeforeQualifierAreSemanticallyIrrelevant() { assertOrder(AbstractVersionTest.X_EQ_Y, "1.0-ga", "1.0.0-ga"); assertOrder(AbstractVersionTest.X_EQ_Y, "1.0.ga", "1.0.0.ga"); assertOrder(AbstractVersionTest.X_EQ_Y, "1.0ga", "1.0.0ga"); @@ -99,7 +99,7 @@ void testTrailingZerosBeforeQualifierAreSemanticallyIrrelevant() { } @Test - void testTrailingDelimitersAreSemanticallyIrrelevant() { + void trailingDelimitersAreSemanticallyIrrelevant() { assertOrder(AbstractVersionTest.X_EQ_Y, "1", "1............."); assertOrder(AbstractVersionTest.X_EQ_Y, "1", "1-------------"); assertOrder(AbstractVersionTest.X_EQ_Y, "1.0", "1............."); @@ -107,7 +107,7 @@ void testTrailingDelimitersAreSemanticallyIrrelevant() { } @Test - void testInitialDelimiters() { + void initialDelimiters() { assertOrder(AbstractVersionTest.X_EQ_Y, "0.1", ".1"); assertOrder(AbstractVersionTest.X_EQ_Y, "0.0.1", "..1"); assertOrder(AbstractVersionTest.X_EQ_Y, "0.1", "-1"); @@ -115,7 +115,7 @@ void testInitialDelimiters() { } @Test - void testConsecutiveDelimiters() { + void consecutiveDelimiters() { assertOrder(AbstractVersionTest.X_EQ_Y, "1.0.1", "1..1"); assertOrder(AbstractVersionTest.X_EQ_Y, "1.0.0.1", "1...1"); assertOrder(AbstractVersionTest.X_EQ_Y, "1.0.1", "1--1"); @@ -123,18 +123,18 @@ void testConsecutiveDelimiters() { } @Test - void testUnlimitedNumberOfVersionComponents() { + void unlimitedNumberOfVersionComponents() { assertOrder(AbstractVersionTest.X_GT_Y, "1.0.1.2.3.4.5.6.7.8.9.0.1.2.10", "1.0.1.2.3.4.5.6.7.8.9.0.1.2.3"); } @Test - void testUnlimitedNumberOfDigitsInNumericComponent() { + void unlimitedNumberOfDigitsInNumericComponent() { assertOrder( AbstractVersionTest.X_GT_Y, "1.1234567890123456789012345678901", "1.123456789012345678901234567891"); } @Test - void testTransitionFromDigitToLetterAndViceVersaIsEquivalentToDelimiter() { + void transitionFromDigitToLetterAndViceVersaIsEquivalentToDelimiter() { assertOrder(AbstractVersionTest.X_EQ_Y, "1alpha10", "1.alpha.10"); assertOrder(AbstractVersionTest.X_EQ_Y, "1alpha10", "1-alpha-10"); @@ -143,7 +143,7 @@ void testTransitionFromDigitToLetterAndViceVersaIsEquivalentToDelimiter() { } @Test - void testWellKnownQualifierOrdering() { + void wellKnownQualifierOrdering() { assertOrder(AbstractVersionTest.X_EQ_Y, "1-alpha1", "1-a1"); assertOrder(AbstractVersionTest.X_LT_Y, "1-alpha", "1-beta"); assertOrder(AbstractVersionTest.X_EQ_Y, "1-beta1", "1-b1"); @@ -171,7 +171,7 @@ void testWellKnownQualifierOrdering() { } @Test - void testWellKnownQualifierVersusUnknownQualifierOrdering() { + void wellKnownQualifierVersusUnknownQualifierOrdering() { assertOrder(AbstractVersionTest.X_GT_Y, "1-abc", "1-alpha"); assertOrder(AbstractVersionTest.X_GT_Y, "1-abc", "1-beta"); assertOrder(AbstractVersionTest.X_GT_Y, "1-abc", "1-milestone"); @@ -182,7 +182,7 @@ void testWellKnownQualifierVersusUnknownQualifierOrdering() { } @Test - void testWellKnownSingleCharQualifiersOnlyRecognizedIfImmediatelyFollowedByNumber() { + void wellKnownSingleCharQualifiersOnlyRecognizedIfImmediatelyFollowedByNumber() { assertOrder(AbstractVersionTest.X_GT_Y, "1.0a", "1.0"); assertOrder(AbstractVersionTest.X_GT_Y, "1.0-a", "1.0"); assertOrder(AbstractVersionTest.X_GT_Y, "1.0.a", "1.0"); @@ -212,14 +212,14 @@ void testWellKnownSingleCharQualifiersOnlyRecognizedIfImmediatelyFollowedByNumbe } @Test - void testUnknownQualifierOrdering() { + void unknownQualifierOrdering() { assertOrder(AbstractVersionTest.X_LT_Y, "1-abc", "1-abcd"); assertOrder(AbstractVersionTest.X_LT_Y, "1-abc", "1-bcd"); assertOrder(AbstractVersionTest.X_GT_Y, "1-abc", "1-aac"); } @Test - void testCaseInsensitiveOrderingOfQualifiers() { + void caseInsensitiveOrderingOfQualifiers() { assertOrder(AbstractVersionTest.X_EQ_Y, "1.alpha", "1.ALPHA"); assertOrder(AbstractVersionTest.X_EQ_Y, "1.alpha", "1.Alpha"); @@ -252,7 +252,7 @@ void testCaseInsensitiveOrderingOfQualifiers() { } @Test - void testCaseInsensitiveOrderingOfQualifiersIsLocaleIndependent() { + void caseInsensitiveOrderingOfQualifiersIsLocaleIndependent() { Locale orig = Locale.getDefault(); try { Locale[] locales = {Locale.ENGLISH, new Locale("tr")}; @@ -266,7 +266,7 @@ void testCaseInsensitiveOrderingOfQualifiersIsLocaleIndependent() { } @Test - void testQualifierVersusNumberOrdering() { + void qualifierVersusNumberOrdering() { assertOrder(AbstractVersionTest.X_LT_Y, "1-ga", "1-1"); assertOrder(AbstractVersionTest.X_LT_Y, "1.ga", "1.1"); assertOrder(AbstractVersionTest.X_EQ_Y, "1-ga", "1.0"); @@ -286,7 +286,7 @@ void testQualifierVersusNumberOrdering() { } @Test - void testVersionEvolution() { + void versionEvolution() { assertSequence( "0.9.9-SNAPSHOT", "0.9.9", @@ -322,7 +322,7 @@ void testVersionEvolution() { } @Test - void testMinimumSegment() { + void minimumSegment() { assertOrder(AbstractVersionTest.X_LT_Y, "1.min", "1.0-alpha-1"); assertOrder(AbstractVersionTest.X_LT_Y, "1.min", "1.0-SNAPSHOT"); assertOrder(AbstractVersionTest.X_LT_Y, "1.min", "1.0"); @@ -335,7 +335,7 @@ void testMinimumSegment() { } @Test - void testMaximumSegment() { + void maximumSegment() { assertOrder(AbstractVersionTest.X_GT_Y, "1.max", "1.0-alpha-1"); assertOrder(AbstractVersionTest.X_GT_Y, "1.max", "1.0-SNAPSHOT"); assertOrder(AbstractVersionTest.X_GT_Y, "1.max", "1.0"); @@ -351,11 +351,11 @@ void testMaximumSegment() { * UT for MRESOLVER-314. * * Generates random UUID string based versions and tries to sort them. While this test is not as reliable - * as {@link #testCompareUuidVersionStringStream()}, it covers broader range and in case it fails it records + * as {@link #compareUuidVersionStringStream()}, it covers broader range and in case it fails it records * the failed array, so we can investigate more. */ @Test - void testCompareUuidRandom() { + void compareUuidRandom() { for (int j = 0; j < 32; j++) { ArrayList versions = new ArrayList<>(); for (int i = 0; i < 64; i++) { @@ -378,7 +378,7 @@ void testCompareUuidRandom() { * Works on known set that failed before fix, provided by {@link #uuidVersionStringStream()}. */ @Test - void testCompareUuidVersionStringStream() { + void compareUuidVersionStringStream() { // this operation below fails with IAEx if comparison is unstable uuidVersionStringStream().map(this::newVersion).sorted().toList(); } diff --git a/impl/maven-impl/src/test/java/org/apache/maven/impl/cache/SoftIdentityMapTest.java b/impl/maven-impl/src/test/java/org/apache/maven/impl/cache/SoftIdentityMapTest.java index 6f64e1b95c4b..126f7d88e7c3 100644 --- a/impl/maven-impl/src/test/java/org/apache/maven/impl/cache/SoftIdentityMapTest.java +++ b/impl/maven-impl/src/test/java/org/apache/maven/impl/cache/SoftIdentityMapTest.java @@ -29,10 +29,9 @@ import org.junit.jupiter.api.RepeatedTest; import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType; import static org.junit.jupiter.api.Assertions.assertNotSame; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; class SoftIdentityMapTest { private SoftIdentityMap map; @@ -57,9 +56,9 @@ void shouldComputeValueOnlyOnce() { return "different value"; }); - assertEquals("value", result1); - assertEquals("value", result2); - assertEquals(1, computeCount.get()); + assertThat(result1).isEqualTo("value"); + assertThat(result2).isEqualTo("value"); + assertThat(computeCount.get()).isEqualTo(1); } @RepeatedTest(10) @@ -128,14 +127,8 @@ void shouldBeThreadSafe() throws InterruptedException { sink.accept("Final compute count: " + computeCount.get()); sink.accept("Unique results size: " + uniqueResults.size()); - assertEquals( - 1, - computeCount.get(), - "Value should be computed exactly once, but was computed " + computeCount.get() + " times"); - assertEquals( - 1, - uniqueResults.size(), - "All threads should see the same value, but saw " + uniqueResults.size() + " different values"); + assertThat(computeCount.get()).as("Value should be computed exactly once, but was computed " + computeCount.get() + " times").isEqualTo(1); + assertThat(uniqueResults.size()).as("All threads should see the same value, but saw " + uniqueResults.size() + " different values").isEqualTo(1); } @Test @@ -144,7 +137,7 @@ void shouldUseIdentityComparison() { String key1 = new String("key"); String key2 = new String("key"); - assertTrue(key1.equals(key2), "Sanity check: keys should be equal"); + assertThat(key2).as("Sanity check: keys should be equal").isEqualTo(key1); assertNotSame(key1, key2, "Sanity check: keys should be distinct objects"); AtomicInteger computeCount = new AtomicInteger(0); @@ -159,7 +152,7 @@ void shouldUseIdentityComparison() { return "value2"; }); - assertEquals(1, computeCount.get(), "Should compute once for equal but distinct keys"); + assertThat(computeCount.get()).as("Should compute once for equal but distinct keys").isEqualTo(1); } @Test @@ -187,14 +180,14 @@ void shouldHandleSoftReferences() throws InterruptedException { return "new value"; }); - assertEquals(2, computeCount.get(), "Should compute again after original key is garbage collected"); + assertThat(computeCount.get()).as("Should compute again after original key is garbage collected").isEqualTo(2); } @Test void shouldHandleNullInputs() { - assertThrows(NullPointerException.class, () -> map.computeIfAbsent(null, k -> "value")); + assertThatExceptionOfType(NullPointerException.class).isThrownBy(() -> map.computeIfAbsent(null, k -> "value")); Object key = new Object(); - assertThrows(NullPointerException.class, () -> map.computeIfAbsent(key, null)); + assertThatExceptionOfType(NullPointerException.class).isThrownBy(() -> map.computeIfAbsent(key, null)); } } diff --git a/impl/maven-impl/src/test/java/org/apache/maven/impl/model/ComplexActivationTest.java b/impl/maven-impl/src/test/java/org/apache/maven/impl/model/ComplexActivationTest.java index eed8b9fa5ae0..bfc0642a57dd 100644 --- a/impl/maven-impl/src/test/java/org/apache/maven/impl/model/ComplexActivationTest.java +++ b/impl/maven-impl/src/test/java/org/apache/maven/impl/model/ComplexActivationTest.java @@ -32,10 +32,7 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * @@ -49,11 +46,11 @@ class ComplexActivationTest { void setup() { session = ApiRunner.createSession(); builder = session.getService(ModelBuilder.class); - assertNotNull(builder); + assertThat(builder).isNotNull(); } @Test - void testAndConditionInActivation() throws Exception { + void andConditionInActivation() throws Exception { ModelBuilderRequest request = ModelBuilderRequest.builder() .session(session) .requestType(ModelBuilderRequest.RequestType.BUILD_PROJECT) @@ -61,25 +58,25 @@ void testAndConditionInActivation() throws Exception { .systemProperties(Map.of("myproperty", "test")) .build(); ModelBuilderResult result = builder.newSession().build(request); - assertNotNull(result); - assertNotNull(result.getEffectiveModel()); - assertEquals("activated-1", result.getEffectiveModel().getProperties().get("profile.file")); - assertNull(result.getEffectiveModel().getProperties().get("profile.miss")); + assertThat(result).isNotNull(); + assertThat(result.getEffectiveModel()).isNotNull(); + assertThat(result.getEffectiveModel().getProperties().get("profile.file")).isEqualTo("activated-1"); + assertThat(result.getEffectiveModel().getProperties().get("profile.miss")).isNull(); } @Test - public void testConditionExistingAndMissingInActivation() throws Exception { + void conditionExistingAndMissingInActivation() throws Exception { ModelBuilderRequest request = ModelBuilderRequest.builder() .session(session) .requestType(ModelBuilderRequest.RequestType.BUILD_PROJECT) .source(Sources.buildSource(getPom("complexExistsAndMissing"))) .build(); ModelBuilderResult result = builder.newSession().build(request); - assertNotNull(result); - assertTrue(result.getProblemCollector() + assertThat(result).isNotNull(); + assertThat(result.getProblemCollector() .problems() .anyMatch(p -> p.getSeverity() == BuilderProblem.Severity.WARNING - && p.getMessage().contains("The 'missing' assertion will be ignored."))); + && p.getMessage().contains("The 'missing' assertion will be ignored."))).isTrue(); } private Path getPom(String name) { diff --git a/impl/maven-impl/src/test/java/org/apache/maven/impl/model/DefaultDependencyManagementImporterTest.java b/impl/maven-impl/src/test/java/org/apache/maven/impl/model/DefaultDependencyManagementImporterTest.java index 8e30494bf779..c13999742db2 100644 --- a/impl/maven-impl/src/test/java/org/apache/maven/impl/model/DefaultDependencyManagementImporterTest.java +++ b/impl/maven-impl/src/test/java/org/apache/maven/impl/model/DefaultDependencyManagementImporterTest.java @@ -28,7 +28,7 @@ class DefaultDependencyManagementImporterTest { @Test - void testUpdateWithImportedFromDependencyLocationAndBomLocationAreNullDependencyReturned() { + void updateWithImportedFromDependencyLocationAndBomLocationAreNullDependencyReturned() { final Dependency dependency = Dependency.newBuilder().build(); final DependencyManagement depMgmt = DependencyManagement.newBuilder().build(); final Dependency result = DefaultDependencyManagementImporter.updateWithImportedFrom(dependency, depMgmt); @@ -37,7 +37,7 @@ void testUpdateWithImportedFromDependencyLocationAndBomLocationAreNullDependency } @Test - void testUpdateWithImportedFromDependencyManagementAndDependencyHaveSameSourceDependencyImportedFromSameSource() { + void updateWithImportedFromDependencyManagementAndDependencyHaveSameSourceDependencyImportedFromSameSource() { final InputSource source = new InputSource("SINGLE_SOURCE", ""); final Dependency dependency = Dependency.newBuilder() .location("", new InputLocation(1, 1, source)) @@ -54,7 +54,7 @@ void testUpdateWithImportedFromDependencyManagementAndDependencyHaveSameSourceDe } @Test - public void testUpdateWithImportedFromSingleLevelImportedFromSet() { + void updateWithImportedFromSingleLevelImportedFromSet() { // Arrange final InputSource dependencySource = new InputSource("DEPENDENCY", "DEPENDENCY"); final InputSource bomSource = new InputSource("BOM", "BOM"); @@ -75,7 +75,7 @@ public void testUpdateWithImportedFromSingleLevelImportedFromSet() { } @Test - public void testUpdateWithImportedFromMultiLevelImportedFromSetChanged() { + void updateWithImportedFromMultiLevelImportedFromSetChanged() { // Arrange final InputSource bomSource = new InputSource("BOM", "BOM"); final InputSource intermediateSource = @@ -99,7 +99,7 @@ public void testUpdateWithImportedFromMultiLevelImportedFromSetChanged() { } @Test - public void testUpdateWithImportedFromMultiLevelAlreadyFoundInDifferentSourceImportedFromSetMaintained() { + void updateWithImportedFromMultiLevelAlreadyFoundInDifferentSourceImportedFromSetMaintained() { // Arrange final InputSource bomSource = new InputSource("BOM", "BOM"); final InputSource intermediateSource = diff --git a/impl/maven-impl/src/test/java/org/apache/maven/impl/model/DefaultInterpolatorTest.java b/impl/maven-impl/src/test/java/org/apache/maven/impl/model/DefaultInterpolatorTest.java index 9d332e9a5194..70dd57ca19ef 100644 --- a/impl/maven-impl/src/test/java/org/apache/maven/impl/model/DefaultInterpolatorTest.java +++ b/impl/maven-impl/src/test/java/org/apache/maven/impl/model/DefaultInterpolatorTest.java @@ -26,13 +26,13 @@ import org.apache.maven.api.services.InterpolatorException; import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType; class DefaultInterpolatorTest { @Test - void testBasicSubstitution() { + void basicSubstitution() { Map props = new HashMap<>(); props.put("key0", "value0"); props.put("key1", "${value1}"); @@ -40,67 +40,64 @@ void testBasicSubstitution() { performSubstitution(props, Map.of("value1", "sub_value1")::get); - assertEquals("value0", props.get("key0")); - assertEquals("sub_value1", props.get("key1")); - assertEquals("", props.get("key2")); + assertThat(props.get("key0")).isEqualTo("value0"); + assertThat(props.get("key1")).isEqualTo("sub_value1"); + assertThat(props.get("key2")).isEqualTo(""); } @Test - void testBasicSubstitutionWithContext() { + void basicSubstitutionWithContext() { HashMap props = new HashMap<>(); props.put("key0", "value0"); props.put("key1", "${value1}"); performSubstitution(props, Map.of("value1", "sub_value1")::get); - assertEquals("value0", props.get("key0")); - assertEquals("sub_value1", props.get("key1")); + assertThat(props.get("key0")).isEqualTo("value0"); + assertThat(props.get("key1")).isEqualTo("sub_value1"); } @Test - void testSubstitutionFailures() { - assertEquals("a}", substVars("a}", "b")); - assertEquals("${a", substVars("${a", "b")); + void substitutionFailures() { + assertThat(substVars("a}", "b")).isEqualTo("a}"); + assertThat(substVars("${a", "b")).isEqualTo("${a"); } @Test - void testEmptyVariable() { - assertEquals("", substVars("${}", "b")); + void emptyVariable() { + assertThat(substVars("${}", "b")).isEqualTo(""); } @Test - void testInnerSubst() { - assertEquals("c", substVars("${${a}}", "z", Map.of("a", "b", "b", "c"))); + void innerSubst() { + assertThat(substVars("${${a}}", "z", Map.of("a", "b", "b", "c"))).isEqualTo("c"); } @Test - void testSubstLoop() { - assertThrows( - InterpolatorException.class, - () -> substVars("${a}", "a"), - "Expected substVars() to throw an InterpolatorException, but it didn't"); + void substLoop() { + assertThatExceptionOfType(InterpolatorException.class).as("Expected substVars() to throw an InterpolatorException, but it didn't").isThrownBy(() -> substVars("${a}", "a")); } @Test - void testLoopEmpty() { - assertEquals("${a}", substVars("${a}", null, null, null, false)); + void loopEmpty() { + assertThat(substVars("${a}", null, null, null, false)).isEqualTo("${a}"); } @Test - void testLoopEmpty2() { - assertEquals("${a}", substVars("${a}", null, null, null, false)); + void loopEmpty2() { + assertThat(substVars("${a}", null, null, null, false)).isEqualTo("${a}"); } @Test - void testSubstitutionEscape() { - assertEquals("${a}", substVars("$\\{a${#}\\}", "b")); - assertEquals("${a}", substVars("$\\{a\\}${#}", "b")); - assertEquals("${a}", substVars("$\\{a\\}", "b")); - assertEquals("\\\\", substVars("\\\\", "b")); + void substitutionEscape() { + assertThat(substVars("$\\{a${#}\\}", "b")).isEqualTo("${a}"); + assertThat(substVars("$\\{a\\}${#}", "b")).isEqualTo("${a}"); + assertThat(substVars("$\\{a\\}", "b")).isEqualTo("${a}"); + assertThat(substVars("\\\\", "b")).isEqualTo("\\\\"); } @Test - void testSubstitutionOrder() { + void substitutionOrder() { LinkedHashMap map1 = new LinkedHashMap<>(); map1.put("a", "$\\\\{var}"); map1.put("abc", "${ab}c"); @@ -113,39 +110,39 @@ void testSubstitutionOrder() { map2.put("abc", "${ab}c"); performSubstitution(map2); - assertEquals(map1, map2); + assertThat(map2).isEqualTo(map1); } @Test - void testMultipleEscapes() { + void multipleEscapes() { LinkedHashMap map1 = new LinkedHashMap<>(); map1.put("a", "$\\\\{var}"); map1.put("abc", "${ab}c"); map1.put("ab", "${a}b"); performSubstitution(map1); - assertEquals("$\\{var}", map1.get("a")); - assertEquals("$\\{var}b", map1.get("ab")); - assertEquals("$\\{var}bc", map1.get("abc")); + assertThat(map1.get("a")).isEqualTo("$\\{var}"); + assertThat(map1.get("ab")).isEqualTo("$\\{var}b"); + assertThat(map1.get("abc")).isEqualTo("$\\{var}bc"); } @Test - void testPreserveUnresolved() { + void preserveUnresolved() { Map props = new HashMap<>(); props.put("a", "${b}"); - assertEquals("", substVars("${b}", "a", props, null, true)); - assertEquals("${b}", substVars("${b}", "a", props, null, false)); + assertThat(substVars("${b}", "a", props, null, true)).isEqualTo(""); + assertThat(substVars("${b}", "a", props, null, false)).isEqualTo("${b}"); props.put("b", "c"); - assertEquals("c", substVars("${b}", "a", props, null, true)); - assertEquals("c", substVars("${b}", "a", props, null, false)); + assertThat(substVars("${b}", "a", props, null, true)).isEqualTo("c"); + assertThat(substVars("${b}", "a", props, null, false)).isEqualTo("c"); props.put("c", "${d}${d}"); - assertEquals("${d}${d}", substVars("${d}${d}", "c", props, null, false)); + assertThat(substVars("${d}${d}", "c", props, null, false)).isEqualTo("${d}${d}"); } @Test - void testExpansion() { + void expansion() { Map props = new LinkedHashMap<>(); props.put("a", "foo"); props.put("b", ""); @@ -160,17 +157,17 @@ void testExpansion() { performSubstitution(props); - assertEquals("foo", props.get("a_cm")); - assertEquals("bar", props.get("b_cm")); - assertEquals("bar", props.get("c_cm")); + assertThat(props.get("a_cm")).isEqualTo("foo"); + assertThat(props.get("b_cm")).isEqualTo("bar"); + assertThat(props.get("c_cm")).isEqualTo("bar"); - assertEquals("bar", props.get("a_cp")); - assertEquals("", props.get("b_cp")); - assertEquals("", props.get("c_cp")); + assertThat(props.get("a_cp")).isEqualTo("bar"); + assertThat(props.get("b_cp")).isEqualTo(""); + assertThat(props.get("c_cp")).isEqualTo(""); } @Test - void testTernary() { + void ternary() { Map props; props = new LinkedHashMap<>(); @@ -178,7 +175,7 @@ void testTernary() { props.put("bar", "-BAR"); props.put("version", "1.0${release:+${foo}:-${bar}}"); performSubstitution(props); - assertEquals("1.0-BAR", props.get("version")); + assertThat(props.get("version")).isEqualTo("1.0-BAR"); props = new LinkedHashMap<>(); props.put("release", "true"); @@ -186,14 +183,14 @@ void testTernary() { props.put("bar", "-BAR"); props.put("version", "1.0${release:+${foo}:-${bar}}"); performSubstitution(props); - assertEquals("1.0-FOO", props.get("version")); + assertThat(props.get("version")).isEqualTo("1.0-FOO"); props = new LinkedHashMap<>(); props.put("foo", ""); props.put("bar", "-BAR"); props.put("version", "1.0${release:+${foo}:-${bar}}"); performSubstitution(props); - assertEquals("1.0-BAR", props.get("version")); + assertThat(props.get("version")).isEqualTo("1.0-BAR"); props = new LinkedHashMap<>(); props.put("release", "true"); @@ -201,22 +198,22 @@ void testTernary() { props.put("bar", "-BAR"); props.put("version", "1.0${release:+${foo}:-${bar}}"); performSubstitution(props); - assertEquals("1.0", props.get("version")); + assertThat(props.get("version")).isEqualTo("1.0"); props = new LinkedHashMap<>(); props.put("version", "1.0${release:+:--BAR}"); performSubstitution(props); - assertEquals("1.0-BAR", props.get("version")); + assertThat(props.get("version")).isEqualTo("1.0-BAR"); props = new LinkedHashMap<>(); props.put("release", "true"); props.put("version", "1.0${release:+:--BAR}"); performSubstitution(props); - assertEquals("1.0", props.get("version")); + assertThat(props.get("version")).isEqualTo("1.0"); } @Test - void testXdg() { + void xdg() { Map props; props = new LinkedHashMap<>(); @@ -225,7 +222,7 @@ void testXdg() { "maven.user.config", "${env.MAVEN_XDG:+${env.XDG_CONFIG_HOME:-${user.home}/.config/maven}:-${user.home}/.m2}"); performSubstitution(props); - assertEquals("/Users/gnodet/.m2", props.get("maven.user.config")); + assertThat(props.get("maven.user.config")).isEqualTo("/Users/gnodet/.m2"); props = new LinkedHashMap<>(); props.put("user.home", "/Users/gnodet"); @@ -234,7 +231,7 @@ void testXdg() { "${env.MAVEN_XDG:+${env.XDG_CONFIG_HOME:-${user.home}/.config/maven}:-${user.home}/.m2}"); props.put("env.MAVEN_XDG", "true"); performSubstitution(props); - assertEquals("/Users/gnodet/.config/maven", props.get("maven.user.config")); + assertThat(props.get("maven.user.config")).isEqualTo("/Users/gnodet/.config/maven"); props = new LinkedHashMap<>(); props.put("user.home", "/Users/gnodet"); @@ -244,7 +241,7 @@ void testXdg() { props.put("env.MAVEN_XDG", "true"); props.put("env.XDG_CONFIG_HOME", "/Users/gnodet/.xdg/maven"); performSubstitution(props); - assertEquals("/Users/gnodet/.xdg/maven", props.get("maven.user.config")); + assertThat(props.get("maven.user.config")).isEqualTo("/Users/gnodet/.xdg/maven"); } private void performSubstitution(Map props) { diff --git a/impl/maven-impl/src/test/java/org/apache/maven/impl/model/DefaultModelBuilderResultTest.java b/impl/maven-impl/src/test/java/org/apache/maven/impl/model/DefaultModelBuilderResultTest.java index cd7c0c5c2063..99c83362b1bb 100644 --- a/impl/maven-impl/src/test/java/org/apache/maven/impl/model/DefaultModelBuilderResultTest.java +++ b/impl/maven-impl/src/test/java/org/apache/maven/impl/model/DefaultModelBuilderResultTest.java @@ -28,10 +28,7 @@ import org.junit.jupiter.api.Test; import org.mockito.Mockito; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertSame; -import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; class DefaultModelBuilderResultTest { @@ -57,56 +54,56 @@ void setUp() { } @Test - void testModelLifecycle() { + void modelLifecycle() { // Test initial state - assertNull(result.getSource()); - assertNull(result.getFileModel()); - assertNull(result.getRawModel()); - assertNull(result.getEffectiveModel()); - assertEquals(0L, result.getProblemCollector().problems().count()); + assertThat(result.getSource()).isNull(); + assertThat(result.getFileModel()).isNull(); + assertThat(result.getRawModel()).isNull(); + assertThat(result.getEffectiveModel()).isNull(); + assertThat(result.getProblemCollector().problems().count()).isEqualTo(0L); // Set and verify source result.setSource(source); - assertSame(source, result.getSource()); + assertThat(result.getSource()).isSameAs(source); // Set and verify file model result.setFileModel(fileModel); - assertSame(fileModel, result.getFileModel()); + assertThat(result.getFileModel()).isSameAs(fileModel); // Set and verify raw model result.setRawModel(rawModel); - assertSame(rawModel, result.getRawModel()); + assertThat(result.getRawModel()).isSameAs(rawModel); // Set and verify effective model result.setEffectiveModel(effectiveModel); - assertSame(effectiveModel, result.getEffectiveModel()); + assertThat(result.getEffectiveModel()).isSameAs(effectiveModel); } @Test - void testProblemCollection() { + void problemCollection() { ModelProblem problem = mock(ModelProblem.class); Mockito.when(problem.getSeverity()).thenReturn(BuilderProblem.Severity.ERROR); problemCollector.reportProblem(problem); - assertEquals(1, result.getProblemCollector().problems().count()); - assertSame(problem, result.getProblemCollector().problems().findFirst().get()); + assertThat(result.getProblemCollector().problems().count()).isEqualTo(1); + assertThat(result.getProblemCollector().problems().findFirst().get()).isSameAs(problem); } @Test - void testChildrenManagement() { + void childrenManagement() { DefaultModelBuilderResult child1 = new DefaultModelBuilderResult(request, problemCollector); DefaultModelBuilderResult child2 = new DefaultModelBuilderResult(request, problemCollector); result.getChildren().add(child1); result.getChildren().add(child2); - assertEquals(2, result.getChildren().size()); - assertTrue(result.getChildren().contains(child1)); - assertTrue(result.getChildren().contains(child2)); + assertThat(result.getChildren().size()).isEqualTo(2); + assertThat(result.getChildren().contains(child1)).isTrue(); + assertThat(result.getChildren().contains(child2)).isTrue(); } @Test - void testRequestAssociation() { - assertSame(request, result.getRequest()); + void requestAssociation() { + assertThat(result.getRequest()).isSameAs(request); } } diff --git a/impl/maven-impl/src/test/java/org/apache/maven/impl/model/DefaultModelBuilderTest.java b/impl/maven-impl/src/test/java/org/apache/maven/impl/model/DefaultModelBuilderTest.java index 2b012185c4bf..b12183fe65e8 100644 --- a/impl/maven-impl/src/test/java/org/apache/maven/impl/model/DefaultModelBuilderTest.java +++ b/impl/maven-impl/src/test/java/org/apache/maven/impl/model/DefaultModelBuilderTest.java @@ -37,8 +37,7 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; /** * @@ -52,23 +51,23 @@ class DefaultModelBuilderTest { void setup() { session = ApiRunner.createSession(); builder = session.getService(ModelBuilder.class); - assertNotNull(builder); + assertThat(builder).isNotNull(); } @Test - public void testPropertiesAndProfiles() { + void propertiesAndProfiles() { ModelBuilderRequest request = ModelBuilderRequest.builder() .session(session) .requestType(ModelBuilderRequest.RequestType.BUILD_PROJECT) .source(Sources.buildSource(getPom("props-and-profiles"))) .build(); ModelBuilderResult result = builder.newSession().build(request); - assertNotNull(result); - assertEquals("21", result.getEffectiveModel().getProperties().get("maven.compiler.release")); + assertThat(result).isNotNull(); + assertThat(result.getEffectiveModel().getProperties().get("maven.compiler.release")).isEqualTo("21"); } @Test - public void testMergeRepositories() throws Exception { + void mergeRepositories() throws Exception { // this is here only to trigger mainSession creation; unrelated ModelBuilderRequest request = ModelBuilderRequest.builder() .session(session) @@ -89,7 +88,7 @@ public void testMergeRepositories() throws Exception { List repositories; // before merge repositories = (List) repositoriesField.get(state); - assertEquals(1, repositories.size()); // central + assertThat(repositories.size()).isEqualTo(1); // central Model model = Model.newBuilder() .repositories(Arrays.asList( @@ -106,12 +105,12 @@ public void testMergeRepositories() throws Exception { // after merge repositories = (List) repositoriesField.get(state); - assertEquals(3, repositories.size()); - assertEquals("first", repositories.get(0).getId()); - assertEquals("https://some.repo", repositories.get(0).getUrl()); // interpolated - assertEquals("second", repositories.get(1).getId()); - assertEquals("${secondParentRepo}", repositories.get(1).getUrl()); // un-interpolated (no source) - assertEquals("central", repositories.get(2).getId()); // default + assertThat(repositories.size()).isEqualTo(3); + assertThat(repositories.get(0).getId()).isEqualTo("first"); + assertThat(repositories.get(0).getUrl()).isEqualTo("https://some.repo"); // interpolated + assertThat(repositories.get(1).getId()).isEqualTo("second"); + assertThat(repositories.get(1).getUrl()).isEqualTo("${secondParentRepo}"); // un-interpolated (no source) + assertThat(repositories.get(2).getId()).isEqualTo("central"); // default } private Path getPom(String name) { diff --git a/impl/maven-impl/src/test/java/org/apache/maven/impl/model/DefaultModelInterpolatorTest.java b/impl/maven-impl/src/test/java/org/apache/maven/impl/model/DefaultModelInterpolatorTest.java index 7afe7a82e2de..b7a1cceaa9e0 100644 --- a/impl/maven-impl/src/test/java/org/apache/maven/impl/model/DefaultModelInterpolatorTest.java +++ b/impl/maven-impl/src/test/java/org/apache/maven/impl/model/DefaultModelInterpolatorTest.java @@ -56,10 +56,8 @@ import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType; /** */ @@ -71,30 +69,29 @@ class DefaultModelInterpolatorTest { AtomicReference rootDirectory; // used in TestRootLocator below @BeforeEach - public void setUp() { + void setUp() { context = new HashMap<>(); context.put("basedir", "myBasedir"); context.put("anotherdir", "anotherBasedir"); context.put("project.baseUri", "myBaseUri"); - session = ApiRunner.createSession(injector -> { - injector.bindInstance(DefaultModelInterpolatorTest.class, this); - }); + session = ApiRunner.createSession(injector -> + injector.bindInstance(DefaultModelInterpolatorTest.class, this)); interpolator = session.getService(Lookup.class).lookup(DefaultModelInterpolator.class); } protected void assertProblemFree(SimpleProblemCollector collector) { - assertEquals(0, collector.getErrors().size(), "Expected no errors"); - assertEquals(0, collector.getWarnings().size(), "Expected no warnings"); - assertEquals(0, collector.getFatals().size(), "Expected no fatals"); + assertThat(collector.getErrors().size()).as("Expected no errors").isEqualTo(0); + assertThat(collector.getWarnings().size()).as("Expected no warnings").isEqualTo(0); + assertThat(collector.getFatals().size()).as("Expected no fatals").isEqualTo(0); } @SuppressWarnings("SameParameterValue") protected void assertCollectorState( int numFatals, int numErrors, int numWarnings, SimpleProblemCollector collector) { - assertEquals(numErrors, collector.getErrors().size(), "Errors"); - assertEquals(numWarnings, collector.getWarnings().size(), "Warnings"); - assertEquals(numFatals, collector.getFatals().size(), "Fatals"); + assertThat(collector.getErrors().size()).as("Errors").isEqualTo(numErrors); + assertThat(collector.getWarnings().size()).as("Warnings").isEqualTo(numWarnings); + assertThat(collector.getFatals().size()).as("Fatals").isEqualTo(numFatals); } private ModelBuilderRequest.ModelBuilderRequestBuilder createModelBuildingRequest(Map p) { @@ -108,7 +105,7 @@ private ModelBuilderRequest.ModelBuilderRequestBuilder createModelBuildingReques } @Test - public void testDefaultBuildTimestampFormatShouldFormatTimeIn24HourFormat() { + void defaultBuildTimestampFormatShouldFormatTimeIn24HourFormat() { Calendar cal = Calendar.getInstance(); cal.setTimeZone(TimeZone.getTimeZone("Etc/UTC")); cal.set(Calendar.HOUR, 12); @@ -135,12 +132,12 @@ public void testDefaultBuildTimestampFormatShouldFormatTimeIn24HourFormat() { DateTimeFormatter format = DateTimeFormatter.ofPattern(MavenBuildTimestamp.DEFAULT_BUILD_TIMESTAMP_FORMAT) .withZone(ZoneId.of("UTC")); - assertEquals("1976-11-11T00:16:00Z", format.format(firstTestDate)); - assertEquals("1976-11-11T23:16:00Z", format.format(secondTestDate)); + assertThat(format.format(firstTestDate)).isEqualTo("1976-11-11T00:16:00Z"); + assertThat(format.format(secondTestDate)).isEqualTo("1976-11-11T23:16:00Z"); } @Test - public void testDefaultBuildTimestampFormatWithLocalTimeZoneMidnightRollover() { + void defaultBuildTimestampFormatWithLocalTimeZoneMidnightRollover() { Calendar cal = Calendar.getInstance(); cal.setTimeZone(TimeZone.getTimeZone("Europe/Berlin")); @@ -159,12 +156,12 @@ public void testDefaultBuildTimestampFormatWithLocalTimeZoneMidnightRollover() { DateTimeFormatter format = DateTimeFormatter.ofPattern(MavenBuildTimestamp.DEFAULT_BUILD_TIMESTAMP_FORMAT) .withZone(ZoneId.of("UTC")); - assertEquals("2014-06-15T23:16:00Z", format.format(firstTestDate)); - assertEquals("2014-11-16T00:16:00Z", format.format(secondTestDate)); + assertThat(format.format(firstTestDate)).isEqualTo("2014-06-15T23:16:00Z"); + assertThat(format.format(secondTestDate)).isEqualTo("2014-11-16T00:16:00Z"); } @Test - public void testShouldNotThrowExceptionOnReferenceToNonExistentValue() throws Exception { + void shouldNotThrowExceptionOnReferenceToNonExistentValue() throws Exception { Scm scm = Scm.newBuilder().connection("${test}/somepath").build(); Model model = Model.newBuilder().scm(scm).build(); @@ -173,11 +170,11 @@ public void testShouldNotThrowExceptionOnReferenceToNonExistentValue() throws Ex model, Paths.get("."), createModelBuildingRequest(context).build(), collector); assertProblemFree(collector); - assertEquals("${test}/somepath", out.getScm().getConnection()); + assertThat(out.getScm().getConnection()).isEqualTo("${test}/somepath"); } @Test - public void testShouldThrowExceptionOnRecursiveScmConnectionReference() throws Exception { + void shouldThrowExceptionOnRecursiveScmConnectionReference() throws Exception { Scm scm = Scm.newBuilder() .connection("${project.scm.connection}/somepath") .build(); @@ -190,7 +187,7 @@ public void testShouldThrowExceptionOnRecursiveScmConnectionReference() throws E } @Test - public void testShouldNotThrowExceptionOnReferenceToValueContainingNakedExpression() throws Exception { + void shouldNotThrowExceptionOnReferenceToValueContainingNakedExpression() throws Exception { Scm scm = Scm.newBuilder().connection("${test}/somepath").build(); Map props = new HashMap<>(); props.put("test", "test"); @@ -202,7 +199,7 @@ public void testShouldNotThrowExceptionOnReferenceToValueContainingNakedExpressi assertProblemFree(collector); - assertEquals("test/somepath", out.getScm().getConnection()); + assertThat(out.getScm().getConnection()).isEqualTo("test/somepath"); } @Test @@ -217,11 +214,11 @@ void shouldInterpolateOrganizationNameCorrectly() throws Exception { Model out = interpolator.interpolateModel( model, Paths.get("."), createModelBuildingRequest(context).build(), new SimpleProblemCollector()); - assertEquals(orgName + " Tools", out.getName()); + assertThat(out.getName()).isEqualTo(orgName + " Tools"); } @Test - public void shouldInterpolateDependencyVersionToSetSameAsProjectVersion() throws Exception { + void shouldInterpolateDependencyVersionToSetSameAsProjectVersion() throws Exception { Model model = Model.newBuilder() .version("3.8.1") .dependencies(Collections.singletonList( @@ -233,11 +230,11 @@ public void shouldInterpolateDependencyVersionToSetSameAsProjectVersion() throws model, Paths.get("."), createModelBuildingRequest(context).build(), collector); assertCollectorState(0, 0, 0, collector); - assertEquals("3.8.1", (out.getDependencies().get(0)).getVersion()); + assertThat((out.getDependencies().get(0)).getVersion()).isEqualTo("3.8.1"); } @Test - public void testShouldNotInterpolateDependencyVersionWithInvalidReference() throws Exception { + void shouldNotInterpolateDependencyVersionWithInvalidReference() throws Exception { Model model = Model.newBuilder() .version("3.8.1") .dependencies(Collections.singletonList( @@ -249,11 +246,11 @@ public void testShouldNotInterpolateDependencyVersionWithInvalidReference() thro model, Paths.get("."), createModelBuildingRequest(context).build(), collector); assertProblemFree(collector); - assertEquals("${something}", (out.getDependencies().get(0)).getVersion()); + assertThat((out.getDependencies().get(0)).getVersion()).isEqualTo("${something}"); } @Test - public void testTwoReferences() throws Exception { + void twoReferences() throws Exception { Model model = Model.newBuilder() .version("3.8.1") .artifactId("foo") @@ -267,11 +264,11 @@ public void testTwoReferences() throws Exception { model, Paths.get("."), createModelBuildingRequest(context).build(), collector); assertCollectorState(0, 0, 0, collector); - assertEquals("foo-3.8.1", (out.getDependencies().get(0)).getVersion()); + assertThat((out.getDependencies().get(0)).getVersion()).isEqualTo("foo-3.8.1"); } @Test - public void testProperty() throws Exception { + void property() throws Exception { Model model = Model.newBuilder() .version("3.8.1") .artifactId("foo") @@ -288,13 +285,11 @@ public void testProperty() throws Exception { collector); assertProblemFree(collector); - assertEquals( - "file://localhost/anotherBasedir/temp-repo", - (out.getRepositories().get(0)).getUrl()); + assertThat((out.getRepositories().get(0)).getUrl()).isEqualTo("file://localhost/anotherBasedir/temp-repo"); } @Test - public void testBasedirUnx() throws Exception { + void basedirUnx() throws Exception { FileSystem fs = Jimfs.newFileSystem(Configuration.unix()); Path projectBasedir = fs.getPath("projectBasedir"); @@ -310,13 +305,11 @@ public void testBasedirUnx() throws Exception { model, projectBasedir, createModelBuildingRequest(context).build(), collector); assertProblemFree(collector); - assertEquals( - projectBasedir.toAbsolutePath() + "/temp-repo", - (out.getRepositories().get(0)).getUrl()); + assertThat((out.getRepositories().get(0)).getUrl()).isEqualTo(projectBasedir.toAbsolutePath() + "/temp-repo"); } @Test - public void testBasedirWin() throws Exception { + void basedirWin() throws Exception { FileSystem fs = Jimfs.newFileSystem(Configuration.windows()); Path projectBasedir = fs.getPath("projectBasedir"); @@ -332,13 +325,11 @@ public void testBasedirWin() throws Exception { model, projectBasedir, createModelBuildingRequest(context).build(), collector); assertProblemFree(collector); - assertEquals( - projectBasedir.toAbsolutePath() + "/temp-repo", - (out.getRepositories().get(0)).getUrl()); + assertThat((out.getRepositories().get(0)).getUrl()).isEqualTo(projectBasedir.toAbsolutePath() + "/temp-repo"); } @Test - public void testBaseUri() throws Exception { + void baseUri() throws Exception { Path projectBasedir = Paths.get("projectBasedir"); Model model = Model.newBuilder() @@ -354,13 +345,11 @@ public void testBaseUri() throws Exception { model, projectBasedir, createModelBuildingRequest(context).build(), collector); assertProblemFree(collector); - assertEquals( - projectBasedir.resolve("temp-repo").toUri().toString(), - (out.getRepositories().get(0)).getUrl()); + assertThat((out.getRepositories().get(0)).getUrl()).isEqualTo(projectBasedir.resolve("temp-repo").toUri().toString()); } @Test - void testRootDirectory() throws Exception { + void rootDirectory() throws Exception { Path rootDirectory = Paths.get("myRootDirectory"); Model model = Model.newBuilder() @@ -376,11 +365,11 @@ void testRootDirectory() throws Exception { model, rootDirectory, createModelBuildingRequest(context).build(), collector); assertProblemFree(collector); - assertEquals("file:myRootDirectory/temp-repo", (out.getRepositories().get(0)).getUrl()); + assertThat((out.getRepositories().get(0)).getUrl()).isEqualTo("file:myRootDirectory/temp-repo"); } @Test - void testRootDirectoryWithUri() throws Exception { + void rootDirectoryWithUri() throws Exception { Path rootDirectory = Paths.get("myRootDirectory"); Model model = Model.newBuilder() @@ -396,13 +385,11 @@ void testRootDirectoryWithUri() throws Exception { model, rootDirectory, createModelBuildingRequest(context).build(), collector); assertProblemFree(collector); - assertEquals( - rootDirectory.resolve("temp-repo").toUri().toString(), - (out.getRepositories().get(0)).getUrl()); + assertThat((out.getRepositories().get(0)).getUrl()).isEqualTo(rootDirectory.resolve("temp-repo").toUri().toString()); } @Test - void testRootDirectoryWithNull() throws Exception { + void rootDirectoryWithNull() throws Exception { Path projectDirectory = Paths.get("myProjectDirectory"); this.rootDirectory = new AtomicReference<>(null); @@ -415,19 +402,17 @@ void testRootDirectoryWithNull() throws Exception { .build(); final SimpleProblemCollector collector = new SimpleProblemCollector(); - IllegalStateException e = assertThrows( - IllegalStateException.class, - () -> interpolator.interpolateModel( - model, - projectDirectory, - createModelBuildingRequest(context).build(), - collector)); - - assertEquals(RootLocator.UNABLE_TO_FIND_ROOT_PROJECT_MESSAGE, e.getMessage()); + IllegalStateException e = assertThatExceptionOfType(IllegalStateException.class).isThrownBy(() -> interpolator.interpolateModel( + model, + projectDirectory, + createModelBuildingRequest(context).build(), + collector)).actual(); + + assertThat(e.getMessage()).isEqualTo(RootLocator.UNABLE_TO_FIND_ROOT_PROJECT_MESSAGE); } @Test - public void testEnvars() throws Exception { + void envars() throws Exception { context.put("env.HOME", "/path/to/home"); Map modelProperties = new HashMap<>(); @@ -440,11 +425,11 @@ public void testEnvars() throws Exception { model, Paths.get("."), createModelBuildingRequest(context).build(), collector); assertProblemFree(collector); - assertEquals("/path/to/home", out.getProperties().get("outputDirectory")); + assertThat(out.getProperties().get("outputDirectory")).isEqualTo("/path/to/home"); } @Test - public void envarExpressionThatEvaluatesToNullReturnsTheLiteralString() throws Exception { + void envarExpressionThatEvaluatesToNullReturnsTheLiteralString() throws Exception { Map modelProperties = new HashMap<>(); modelProperties.put("outputDirectory", "${env.DOES_NOT_EXIST}"); @@ -456,11 +441,11 @@ public void envarExpressionThatEvaluatesToNullReturnsTheLiteralString() throws E model, Paths.get("."), createModelBuildingRequest(context).build(), collector); assertProblemFree(collector); - assertEquals("${env.DOES_NOT_EXIST}", out.getProperties().get("outputDirectory")); + assertThat(out.getProperties().get("outputDirectory")).isEqualTo("${env.DOES_NOT_EXIST}"); } @Test - public void expressionThatEvaluatesToNullReturnsTheLiteralString() throws Exception { + void expressionThatEvaluatesToNullReturnsTheLiteralString() throws Exception { Map modelProperties = new HashMap<>(); modelProperties.put("outputDirectory", "${DOES_NOT_EXIST}"); @@ -471,11 +456,11 @@ public void expressionThatEvaluatesToNullReturnsTheLiteralString() throws Except model, Paths.get("."), createModelBuildingRequest(context).build(), collector); assertProblemFree(collector); - assertEquals("${DOES_NOT_EXIST}", out.getProperties().get("outputDirectory")); + assertThat(out.getProperties().get("outputDirectory")).isEqualTo("${DOES_NOT_EXIST}"); } @Test - public void shouldInterpolateSourceDirectoryReferencedFromResourceDirectoryCorrectly() throws Exception { + void shouldInterpolateSourceDirectoryReferencedFromResourceDirectoryCorrectly() throws Exception { Model model = Model.newBuilder() .build(Build.newBuilder() .sourceDirectory("correct") @@ -493,11 +478,11 @@ public void shouldInterpolateSourceDirectoryReferencedFromResourceDirectoryCorre List outResources = out.getBuild().getResources(); Iterator resIt = outResources.iterator(); - assertEquals(model.getBuild().getSourceDirectory(), resIt.next().getDirectory()); + assertThat(resIt.next().getDirectory()).isEqualTo(model.getBuild().getSourceDirectory()); } @Test - public void shouldInterpolateUnprefixedBasedirExpression() throws Exception { + void shouldInterpolateUnprefixedBasedirExpression() throws Exception { Path basedir = Paths.get("/test/path"); Model model = Model.newBuilder() .dependencies(Collections.singletonList(Dependency.newBuilder() @@ -511,15 +496,13 @@ public void shouldInterpolateUnprefixedBasedirExpression() throws Exception { assertProblemFree(collector); List rDeps = result.getDependencies(); - assertNotNull(rDeps); - assertEquals(1, rDeps.size()); - assertEquals( - basedir.resolve("artifact.jar").toAbsolutePath(), - Paths.get(rDeps.get(0).getSystemPath()).toAbsolutePath()); + assertThat(rDeps).isNotNull(); + assertThat(rDeps.size()).isEqualTo(1); + assertThat(Paths.get(rDeps.get(0).getSystemPath()).toAbsolutePath()).isEqualTo(basedir.resolve("artifact.jar").toAbsolutePath()); } @Test - public void testRecursiveExpressionCycleNPE() throws Exception { + void recursiveExpressionCycleNPE() throws Exception { Map props = new HashMap<>(); props.put("aa", "${bb}"); props.put("bb", "${aa}"); @@ -532,12 +515,12 @@ public void testRecursiveExpressionCycleNPE() throws Exception { interpolator.interpolateModel(model, null, request, collector); assertCollectorState(0, 2, 0, collector); - assertTrue(collector.getErrors().get(0).contains("recursive variable reference")); + assertThat(collector.getErrors().get(0).contains("recursive variable reference")).isTrue(); } @Disabled("per def cannot be recursive: ${basedir} is immediately going for project.basedir") @Test - public void testRecursiveExpressionCycleBaseDir() throws Exception { + void recursiveExpressionCycleBaseDir() throws Exception { Map props = new HashMap<>(); props.put("basedir", "${basedir}"); ModelBuilderRequest request = createModelBuildingRequest(Map.of()).build(); @@ -549,8 +532,7 @@ public void testRecursiveExpressionCycleBaseDir() throws Exception { interpolator.interpolateModel(model, null, request, collector); assertCollectorState(0, 1, 0, collector); - assertEquals( - "recursive variable reference: basedir", collector.getErrors().get(0)); + assertThat(collector.getErrors().get(0)).isEqualTo("recursive variable reference: basedir"); } @Test @@ -572,7 +554,7 @@ void shouldIgnorePropertiesWithPomPrefix() throws Exception { collector); assertCollectorState(0, 0, 0, collector); - assertEquals(uninterpolatedName, out.getName()); + assertThat(out.getName()).isEqualTo(uninterpolatedName); } @Provides diff --git a/impl/maven-impl/src/test/java/org/apache/maven/impl/model/DefaultModelValidatorTest.java b/impl/maven-impl/src/test/java/org/apache/maven/impl/model/DefaultModelValidatorTest.java index 06947221f3b5..21cc1409b10a 100644 --- a/impl/maven-impl/src/test/java/org/apache/maven/impl/model/DefaultModelValidatorTest.java +++ b/impl/maven-impl/src/test/java/org/apache/maven/impl/model/DefaultModelValidatorTest.java @@ -29,9 +29,7 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** */ @@ -42,7 +40,7 @@ class DefaultModelValidatorTest { private Model read(String pom) throws Exception { String resource = "/poms/validation/" + pom; try (InputStream is = getClass().getResourceAsStream(resource)) { - assertNotNull(is, "missing resource: " + resource); + assertThat(is).as("missing resource: " + resource).isNotNull(); return new MavenStaxReader().read(is); } } @@ -84,7 +82,7 @@ private SimpleProblemCollector validateRaw(String pom, int level) throws Excepti } private void assertContains(String msg, String substring) { - assertTrue(msg.contains(substring), "\"" + substring + "\" was not found in: " + msg); + assertThat(msg.contains(substring)).as("\"" + substring + "\" was not found in: " + msg).isTrue(); } @BeforeEach @@ -98,265 +96,241 @@ void tearDown() throws Exception { } private void assertViolations(SimpleProblemCollector result, int fatals, int errors, int warnings) { - assertEquals(fatals, result.getFatals().size(), String.valueOf(result.getFatals())); - assertEquals(errors, result.getErrors().size(), String.valueOf(result.getErrors())); - assertEquals(warnings, result.getWarnings().size(), String.valueOf(result.getWarnings())); + assertThat(result.getFatals().size()).as(String.valueOf(result.getFatals())).isEqualTo(fatals); + assertThat(result.getErrors().size()).as(String.valueOf(result.getErrors())).isEqualTo(errors); + assertThat(result.getWarnings().size()).as(String.valueOf(result.getWarnings())).isEqualTo(warnings); } @Test - void testMissingModelVersion() throws Exception { + void missingModelVersion() throws Exception { SimpleProblemCollector result = validate("missing-modelVersion-pom.xml"); assertViolations(result, 0, 1, 0); - assertEquals("'modelVersion' is missing.", result.getErrors().get(0)); + assertThat(result.getErrors().get(0)).isEqualTo("'modelVersion' is missing."); } @Test - void testBadModelVersion() throws Exception { + void badModelVersion() throws Exception { SimpleProblemCollector result = validateFile("bad-modelVersion.xml"); assertViolations(result, 1, 0, 0); - assertTrue(result.getFatals().get(0).contains("modelVersion")); + assertThat(result.getFatals().get(0).contains("modelVersion")).isTrue(); } @Test - void testModelVersionMessage() throws Exception { + void modelVersionMessage() throws Exception { SimpleProblemCollector result = validateFile("modelVersion-4_0.xml"); assertViolations(result, 0, 1, 0); - assertTrue(result.getErrors().get(0).contains("'modelVersion' must be one of")); + assertThat(result.getErrors().get(0).contains("'modelVersion' must be one of")).isTrue(); } @Test - void testMissingArtifactId() throws Exception { + void missingArtifactId() throws Exception { SimpleProblemCollector result = validate("missing-artifactId-pom.xml"); assertViolations(result, 0, 1, 0); - assertEquals("'artifactId' is missing.", result.getErrors().get(0)); + assertThat(result.getErrors().get(0)).isEqualTo("'artifactId' is missing."); } @Test - void testMissingGroupId() throws Exception { + void missingGroupId() throws Exception { SimpleProblemCollector result = validate("missing-groupId-pom.xml"); assertViolations(result, 0, 1, 0); - assertEquals("'groupId' is missing.", result.getErrors().get(0)); + assertThat(result.getErrors().get(0)).isEqualTo("'groupId' is missing."); } @Test - void testInvalidCoordinateIds() throws Exception { + void invalidCoordinateIds() throws Exception { SimpleProblemCollector result = validate("invalid-coordinate-ids-pom.xml"); assertViolations(result, 0, 2, 0); - assertEquals( - "'groupId' with value 'o/a/m' does not match a valid coordinate id pattern.", - result.getErrors().get(0)); + assertThat(result.getErrors().get(0)).isEqualTo("'groupId' with value 'o/a/m' does not match a valid coordinate id pattern."); - assertEquals( - "'artifactId' with value 'm$-do$' does not match a valid coordinate id pattern.", - result.getErrors().get(1)); + assertThat(result.getErrors().get(1)).isEqualTo("'artifactId' with value 'm$-do$' does not match a valid coordinate id pattern."); } @Test - void testMissingType() throws Exception { + void missingType() throws Exception { SimpleProblemCollector result = validate("missing-type-pom.xml"); assertViolations(result, 0, 1, 0); - assertEquals("'packaging' is missing.", result.getErrors().get(0)); + assertThat(result.getErrors().get(0)).isEqualTo("'packaging' is missing."); } @Test - void testMissingVersion() throws Exception { + void missingVersion() throws Exception { SimpleProblemCollector result = validate("missing-version-pom.xml"); assertViolations(result, 0, 1, 0); - assertEquals("'version' is missing.", result.getErrors().get(0)); + assertThat(result.getErrors().get(0)).isEqualTo("'version' is missing."); } @Test - void testInvalidAggregatorPackaging() throws Exception { + void invalidAggregatorPackaging() throws Exception { SimpleProblemCollector result = validate("invalid-aggregator-packaging-pom.xml"); assertViolations(result, 0, 1, 0); - assertTrue(result.getErrors().get(0).contains("Aggregator projects require 'pom' as packaging.")); + assertThat(result.getErrors().get(0).contains("Aggregator projects require 'pom' as packaging.")).isTrue(); } @Test - void testMissingDependencyArtifactId() throws Exception { + void missingDependencyArtifactId() throws Exception { SimpleProblemCollector result = validate("missing-dependency-artifactId-pom.xml"); assertViolations(result, 0, 1, 0); - assertTrue( - result.getErrors() - .get(0) - .contains( - "'dependencies.dependency.artifactId' for groupId='groupId', artifactId=, type='jar' is missing")); + assertThat(result.getErrors() + .get(0) + .contains( + "'dependencies.dependency.artifactId' for groupId='groupId', artifactId=, type='jar' is missing")).isTrue(); } @Test - void testMissingDependencyGroupId() throws Exception { + void missingDependencyGroupId() throws Exception { SimpleProblemCollector result = validate("missing-dependency-groupId-pom.xml"); assertViolations(result, 0, 1, 0); - assertTrue( - result.getErrors() - .get(0) - .contains( - "'dependencies.dependency.groupId' for groupId=, artifactId='artifactId', type='jar' is missing")); + assertThat(result.getErrors() + .get(0) + .contains( + "'dependencies.dependency.groupId' for groupId=, artifactId='artifactId', type='jar' is missing")).isTrue(); } @Test - void testMissingDependencyVersion() throws Exception { + void missingDependencyVersion() throws Exception { SimpleProblemCollector result = validate("missing-dependency-version-pom.xml"); assertViolations(result, 0, 1, 0); - assertTrue( - result.getErrors() - .get(0) - .contains( - "'dependencies.dependency.version' for groupId='groupId', artifactId='artifactId', type='jar' is missing")); + assertThat(result.getErrors() + .get(0) + .contains( + "'dependencies.dependency.version' for groupId='groupId', artifactId='artifactId', type='jar' is missing")).isTrue(); } @Test - void testMissingDependencyManagementArtifactId() throws Exception { + void missingDependencyManagementArtifactId() throws Exception { SimpleProblemCollector result = validate("missing-dependency-mgmt-artifactId-pom.xml"); assertViolations(result, 0, 1, 0); - assertTrue( - result.getErrors() - .get(0) - .contains( - "'dependencyManagement.dependencies.dependency.artifactId' for groupId='groupId', artifactId=, type='jar' is missing")); + assertThat(result.getErrors() + .get(0) + .contains( + "'dependencyManagement.dependencies.dependency.artifactId' for groupId='groupId', artifactId=, type='jar' is missing")).isTrue(); } @Test - void testMissingDependencyManagementGroupId() throws Exception { + void missingDependencyManagementGroupId() throws Exception { SimpleProblemCollector result = validate("missing-dependency-mgmt-groupId-pom.xml"); assertViolations(result, 0, 1, 0); - assertTrue( - result.getErrors() - .get(0) - .contains( - "'dependencyManagement.dependencies.dependency.groupId' for groupId=, artifactId='artifactId', type='jar' is missing")); + assertThat(result.getErrors() + .get(0) + .contains( + "'dependencyManagement.dependencies.dependency.groupId' for groupId=, artifactId='artifactId', type='jar' is missing")).isTrue(); } @Test - void testMissingAll() throws Exception { + void missingAll() throws Exception { SimpleProblemCollector result = validate("missing-1-pom.xml"); assertViolations(result, 0, 4, 0); List messages = result.getErrors(); - assertTrue(messages.contains("'modelVersion' is missing.")); - assertTrue(messages.contains("'groupId' is missing.")); - assertTrue(messages.contains("'artifactId' is missing.")); - assertTrue(messages.contains("'version' is missing.")); + assertThat(messages.contains("'modelVersion' is missing.")).isTrue(); + assertThat(messages.contains("'groupId' is missing.")).isTrue(); + assertThat(messages.contains("'artifactId' is missing.")).isTrue(); + assertThat(messages.contains("'version' is missing.")).isTrue(); // type is inherited from the super pom } @Test - void testMissingPluginArtifactId() throws Exception { + void missingPluginArtifactId() throws Exception { SimpleProblemCollector result = validate("missing-plugin-artifactId-pom.xml"); assertViolations(result, 0, 1, 0); - assertEquals( - "'build.plugins.plugin.artifactId' is missing.", - result.getErrors().get(0)); + assertThat(result.getErrors().get(0)).isEqualTo("'build.plugins.plugin.artifactId' is missing."); } @Test - void testEmptyPluginVersion() throws Exception { + void emptyPluginVersion() throws Exception { SimpleProblemCollector result = validate("empty-plugin-version.xml"); assertViolations(result, 0, 1, 0); - assertEquals( - "'build.plugins.plugin.version' for org.apache.maven.plugins:maven-it-plugin" - + " must be a valid version but is ''.", - result.getErrors().get(0)); + assertThat(result.getErrors().get(0)).isEqualTo("'build.plugins.plugin.version' for org.apache.maven.plugins:maven-it-plugin" + + " must be a valid version but is ''."); } @Test - void testMissingRepositoryId() throws Exception { + void missingRepositoryId() throws Exception { SimpleProblemCollector result = validateFile("missing-repository-id-pom.xml", ModelValidator.VALIDATION_LEVEL_STRICT); assertViolations(result, 0, 4, 0); - assertEquals( - "'repositories.repository.id' is missing.", result.getErrors().get(0)); + assertThat(result.getErrors().get(0)).isEqualTo("'repositories.repository.id' is missing."); - assertEquals( - "'repositories.repository.[null].url' is missing.", - result.getErrors().get(1)); + assertThat(result.getErrors().get(1)).isEqualTo("'repositories.repository.[null].url' is missing."); - assertEquals( - "'pluginRepositories.pluginRepository.id' is missing.", - result.getErrors().get(2)); + assertThat(result.getErrors().get(2)).isEqualTo("'pluginRepositories.pluginRepository.id' is missing."); - assertEquals( - "'pluginRepositories.pluginRepository.[null].url' is missing.", - result.getErrors().get(3)); + assertThat(result.getErrors().get(3)).isEqualTo("'pluginRepositories.pluginRepository.[null].url' is missing."); } @Test - void testMissingResourceDirectory() throws Exception { + void missingResourceDirectory() throws Exception { SimpleProblemCollector result = validate("missing-resource-directory-pom.xml"); assertViolations(result, 0, 2, 0); - assertEquals( - "'build.resources.resource.directory' is missing.", - result.getErrors().get(0)); + assertThat(result.getErrors().get(0)).isEqualTo("'build.resources.resource.directory' is missing."); - assertEquals( - "'build.testResources.testResource.directory' is missing.", - result.getErrors().get(1)); + assertThat(result.getErrors().get(1)).isEqualTo("'build.testResources.testResource.directory' is missing."); } @Test - void testBadPluginDependencyScope() throws Exception { + void badPluginDependencyScope() throws Exception { SimpleProblemCollector result = validate("bad-plugin-dependency-scope.xml"); assertViolations(result, 0, 3, 0); - assertTrue(result.getErrors().get(0).contains("groupId='test', artifactId='d'")); + assertThat(result.getErrors().get(0).contains("groupId='test', artifactId='d'")).isTrue(); - assertTrue(result.getErrors().get(1).contains("groupId='test', artifactId='e'")); + assertThat(result.getErrors().get(1).contains("groupId='test', artifactId='e'")).isTrue(); - assertTrue(result.getErrors().get(2).contains("groupId='test', artifactId='f'")); + assertThat(result.getErrors().get(2).contains("groupId='test', artifactId='f'")).isTrue(); } @Test - void testBadDependencyScope() throws Exception { + void badDependencyScope() throws Exception { SimpleProblemCollector result = validate("bad-dependency-scope.xml"); assertViolations(result, 0, 0, 2); - assertTrue(result.getWarnings().get(0).contains("groupId='test', artifactId='f'")); + assertThat(result.getWarnings().get(0).contains("groupId='test', artifactId='f'")).isTrue(); - assertTrue(result.getWarnings().get(1).contains("groupId='test', artifactId='g'")); + assertThat(result.getWarnings().get(1).contains("groupId='test', artifactId='g'")).isTrue(); } @Test - void testBadDependencyManagementScope() throws Exception { + void badDependencyManagementScope() throws Exception { SimpleProblemCollector result = validate("bad-dependency-management-scope.xml"); assertViolations(result, 0, 0, 1); @@ -365,7 +339,7 @@ void testBadDependencyManagementScope() throws Exception { } @Test - void testBadDependencyVersion() throws Exception { + void badDependencyVersion() throws Exception { SimpleProblemCollector result = validate("bad-dependency-version.xml"); assertViolations(result, 0, 2, 0); @@ -379,37 +353,37 @@ void testBadDependencyVersion() throws Exception { } @Test - void testDuplicateModule() throws Exception { + void duplicateModule() throws Exception { SimpleProblemCollector result = validateFile("duplicate-module.xml"); assertViolations(result, 0, 1, 0); - assertTrue(result.getErrors().get(0).contains("child")); + assertThat(result.getErrors().get(0).contains("child")).isTrue(); } @Test - void testInvalidProfileId() throws Exception { + void invalidProfileId() throws Exception { SimpleProblemCollector result = validateFile("invalid-profile-ids.xml"); assertViolations(result, 0, 4, 0); - assertTrue(result.getErrors().get(0).contains("+invalid-id")); - assertTrue(result.getErrors().get(1).contains("-invalid-id")); - assertTrue(result.getErrors().get(2).contains("!invalid-id")); - assertTrue(result.getErrors().get(3).contains("?invalid-id")); + assertThat(result.getErrors().get(0).contains("+invalid-id")).isTrue(); + assertThat(result.getErrors().get(1).contains("-invalid-id")).isTrue(); + assertThat(result.getErrors().get(2).contains("!invalid-id")).isTrue(); + assertThat(result.getErrors().get(3).contains("?invalid-id")).isTrue(); } @Test - void testDuplicateProfileId() throws Exception { + void duplicateProfileId() throws Exception { SimpleProblemCollector result = validateFile("duplicate-profile-id.xml"); assertViolations(result, 0, 1, 0); - assertTrue(result.getErrors().get(0).contains("non-unique-id")); + assertThat(result.getErrors().get(0).contains("non-unique-id")).isTrue(); } @Test - void testBadPluginVersion() throws Exception { + void badPluginVersion() throws Exception { SimpleProblemCollector result = validate("bad-plugin-version.xml"); assertViolations(result, 0, 4, 0); @@ -426,26 +400,26 @@ void testBadPluginVersion() throws Exception { } @Test - void testDistributionManagementStatus() throws Exception { + void distributionManagementStatus() throws Exception { SimpleProblemCollector result = validate("distribution-management-status.xml"); assertViolations(result, 0, 1, 0); - assertTrue(result.getErrors().get(0).contains("distributionManagement.status")); + assertThat(result.getErrors().get(0).contains("distributionManagement.status")).isTrue(); } @Test - void testIncompleteParent() throws Exception { + void incompleteParent() throws Exception { SimpleProblemCollector result = validateRaw("incomplete-parent.xml"); assertViolations(result, 3, 0, 0); - assertTrue(result.getFatals().get(0).contains("parent.groupId")); - assertTrue(result.getFatals().get(1).contains("parent.artifactId")); - assertTrue(result.getFatals().get(2).contains("parent.version")); + assertThat(result.getFatals().get(0).contains("parent.groupId")).isTrue(); + assertThat(result.getFatals().get(1).contains("parent.artifactId")).isTrue(); + assertThat(result.getFatals().get(2).contains("parent.version")).isTrue(); } @Test - void testHardCodedSystemPath() throws Exception { + void hardCodedSystemPath() throws Exception { SimpleProblemCollector result = validateFile("hard-coded-system-path.xml"); assertViolations(result, 0, 0, 3); @@ -462,28 +436,28 @@ void testHardCodedSystemPath() throws Exception { } @Test - void testEmptyModule() throws Exception { + void emptyModule() throws Exception { SimpleProblemCollector result = validate("empty-module.xml"); assertViolations(result, 0, 1, 0); - assertTrue(result.getErrors().get(0).contains("'modules.module[0]' has been specified without a path")); + assertThat(result.getErrors().get(0).contains("'modules.module[0]' has been specified without a path")).isTrue(); } @Test - void testDuplicatePlugin() throws Exception { + void duplicatePlugin() throws Exception { SimpleProblemCollector result = validateFile("duplicate-plugin.xml"); assertViolations(result, 0, 4, 0); - assertTrue(result.getErrors().get(0).contains("duplicate declaration of plugin test:duplicate")); - assertTrue(result.getErrors().get(1).contains("duplicate declaration of plugin test:managed-duplicate")); - assertTrue(result.getErrors().get(2).contains("duplicate declaration of plugin profile:duplicate")); - assertTrue(result.getErrors().get(3).contains("duplicate declaration of plugin profile:managed-duplicate")); + assertThat(result.getErrors().get(0).contains("duplicate declaration of plugin test:duplicate")).isTrue(); + assertThat(result.getErrors().get(1).contains("duplicate declaration of plugin test:managed-duplicate")).isTrue(); + assertThat(result.getErrors().get(2).contains("duplicate declaration of plugin profile:duplicate")).isTrue(); + assertThat(result.getErrors().get(3).contains("duplicate declaration of plugin profile:managed-duplicate")).isTrue(); } @Test - void testDuplicatePluginExecution() throws Exception { + void duplicatePluginExecution() throws Exception { SimpleProblemCollector result = validateFile("duplicate-plugin-execution.xml"); assertViolations(result, 0, 4, 0); @@ -495,7 +469,7 @@ void testDuplicatePluginExecution() throws Exception { } @Test - void testReservedRepositoryId() throws Exception { + void reservedRepositoryId() throws Exception { SimpleProblemCollector result = validate("reserved-repository-id.xml"); assertViolations(result, 0, 4, 0); @@ -507,43 +481,43 @@ void testReservedRepositoryId() throws Exception { } @Test - void testMissingPluginDependencyGroupId() throws Exception { + void missingPluginDependencyGroupId() throws Exception { SimpleProblemCollector result = validate("missing-plugin-dependency-groupId.xml"); assertViolations(result, 0, 1, 0); - assertTrue(result.getErrors().get(0).contains("groupId=, artifactId='a',")); + assertThat(result.getErrors().get(0).contains("groupId=, artifactId='a',")).isTrue(); } @Test - void testMissingPluginDependencyArtifactId() throws Exception { + void missingPluginDependencyArtifactId() throws Exception { SimpleProblemCollector result = validate("missing-plugin-dependency-artifactId.xml"); assertViolations(result, 0, 1, 0); - assertTrue(result.getErrors().get(0).contains("groupId='test', artifactId=,")); + assertThat(result.getErrors().get(0).contains("groupId='test', artifactId=,")).isTrue(); } @Test - void testMissingPluginDependencyVersion() throws Exception { + void missingPluginDependencyVersion() throws Exception { SimpleProblemCollector result = validate("missing-plugin-dependency-version.xml"); assertViolations(result, 0, 1, 0); - assertTrue(result.getErrors().get(0).contains("groupId='test', artifactId='a',")); + assertThat(result.getErrors().get(0).contains("groupId='test', artifactId='a',")).isTrue(); } @Test - void testBadPluginDependencyVersion() throws Exception { + void badPluginDependencyVersion() throws Exception { SimpleProblemCollector result = validate("bad-plugin-dependency-version.xml"); assertViolations(result, 0, 1, 0); - assertTrue(result.getErrors().get(0).contains("groupId='test', artifactId='b'")); + assertThat(result.getErrors().get(0).contains("groupId='test', artifactId='b'")).isTrue(); } @Test - void testBadVersion() throws Exception { + void badVersion() throws Exception { SimpleProblemCollector result = validate("bad-version.xml"); assertViolations(result, 0, 1, 0); @@ -552,7 +526,7 @@ void testBadVersion() throws Exception { } @Test - void testBadSnapshotVersion() throws Exception { + void badSnapshotVersion() throws Exception { SimpleProblemCollector result = validate("bad-snapshot-version.xml"); assertViolations(result, 0, 1, 0); @@ -561,7 +535,7 @@ void testBadSnapshotVersion() throws Exception { } @Test - void testBadRepositoryId() throws Exception { + void badRepositoryId() throws Exception { SimpleProblemCollector result = validate("bad-repository-id.xml"); assertViolations(result, 0, 4, 0); @@ -580,7 +554,7 @@ void testBadRepositoryId() throws Exception { } @Test - void testBadDependencyExclusionId() throws Exception { + void badDependencyExclusionId() throws Exception { SimpleProblemCollector result = validateEffective("bad-dependency-exclusion-id.xml", ModelValidator.VALIDATION_LEVEL_MAVEN_2_0); @@ -601,7 +575,7 @@ void testBadDependencyExclusionId() throws Exception { } @Test - void testMissingDependencyExclusionId() throws Exception { + void missingDependencyExclusionId() throws Exception { SimpleProblemCollector result = validate("missing-dependency-exclusion-id.xml"); assertViolations(result, 0, 0, 2); @@ -615,7 +589,7 @@ void testMissingDependencyExclusionId() throws Exception { } @Test - void testBadImportScopeType() throws Exception { + void badImportScopeType() throws Exception { SimpleProblemCollector result = validateFile("bad-import-scope-type.xml"); assertViolations(result, 0, 0, 1); @@ -626,7 +600,7 @@ void testBadImportScopeType() throws Exception { } @Test - void testBadImportScopeClassifier() throws Exception { + void badImportScopeClassifier() throws Exception { SimpleProblemCollector result = validateFile("bad-import-scope-classifier.xml"); assertViolations(result, 0, 1, 0); @@ -637,7 +611,7 @@ void testBadImportScopeClassifier() throws Exception { } @Test - void testSystemPathRefersToProjectBasedir() throws Exception { + void systemPathRefersToProjectBasedir() throws Exception { SimpleProblemCollector result = validateFile("basedir-system-path.xml"); assertViolations(result, 0, 0, 4); @@ -657,62 +631,52 @@ void testSystemPathRefersToProjectBasedir() throws Exception { } @Test - void testInvalidVersionInPluginManagement() throws Exception { + void invalidVersionInPluginManagement() throws Exception { SimpleProblemCollector result = validateFile("raw-model/missing-plugin-version-pluginManagement.xml"); assertViolations(result, 1, 0, 0); - assertEquals( - "'build.pluginManagement.plugins.plugin.(groupId:artifactId)' version of a plugin must be defined. ", - result.getFatals().get(0)); + assertThat(result.getFatals().get(0)).isEqualTo("'build.pluginManagement.plugins.plugin.(groupId:artifactId)' version of a plugin must be defined. "); } @Test - void testInvalidGroupIdInPluginManagement() throws Exception { + void invalidGroupIdInPluginManagement() throws Exception { SimpleProblemCollector result = validateFile("raw-model/missing-groupId-pluginManagement.xml"); assertViolations(result, 1, 0, 0); - assertEquals( - "'build.pluginManagement.plugins.plugin.(groupId:artifactId)' groupId of a plugin must be defined. ", - result.getFatals().get(0)); + assertThat(result.getFatals().get(0)).isEqualTo("'build.pluginManagement.plugins.plugin.(groupId:artifactId)' groupId of a plugin must be defined. "); } @Test - void testInvalidArtifactIdInPluginManagement() throws Exception { + void invalidArtifactIdInPluginManagement() throws Exception { SimpleProblemCollector result = validateFile("raw-model/missing-artifactId-pluginManagement.xml"); assertViolations(result, 1, 0, 0); - assertEquals( - "'build.pluginManagement.plugins.plugin.(groupId:artifactId)' artifactId of a plugin must be defined. ", - result.getFatals().get(0)); + assertThat(result.getFatals().get(0)).isEqualTo("'build.pluginManagement.plugins.plugin.(groupId:artifactId)' artifactId of a plugin must be defined. "); } @Test - void testInvalidGroupAndArtifactIdInPluginManagement() throws Exception { + void invalidGroupAndArtifactIdInPluginManagement() throws Exception { SimpleProblemCollector result = validateFile("raw-model/missing-ga-pluginManagement.xml"); assertViolations(result, 2, 0, 0); - assertEquals( - "'build.pluginManagement.plugins.plugin.(groupId:artifactId)' groupId of a plugin must be defined. ", - result.getFatals().get(0)); + assertThat(result.getFatals().get(0)).isEqualTo("'build.pluginManagement.plugins.plugin.(groupId:artifactId)' groupId of a plugin must be defined. "); - assertEquals( - "'build.pluginManagement.plugins.plugin.(groupId:artifactId)' artifactId of a plugin must be defined. ", - result.getFatals().get(1)); + assertThat(result.getFatals().get(1)).isEqualTo("'build.pluginManagement.plugins.plugin.(groupId:artifactId)' artifactId of a plugin must be defined. "); } @Test - void testMissingReportPluginVersion() throws Exception { + void missingReportPluginVersion() throws Exception { SimpleProblemCollector result = validate("missing-report-version-pom.xml"); assertViolations(result, 0, 0, 0); } @Test - void testDeprecatedDependencyMetaversionsLatestAndRelease() throws Exception { + void deprecatedDependencyMetaversionsLatestAndRelease() throws Exception { SimpleProblemCollector result = validateFile("deprecated-dependency-metaversions-latest-and-release.xml"); assertViolations(result, 0, 0, 2); @@ -726,99 +690,85 @@ void testDeprecatedDependencyMetaversionsLatestAndRelease() throws Exception { } @Test - void testSelfReferencingDependencyInRawModel() throws Exception { + void selfReferencingDependencyInRawModel() throws Exception { SimpleProblemCollector result = validateFile("raw-model/self-referencing.xml"); assertViolations(result, 1, 0, 0); - assertEquals( - "'dependencies.dependency[com.example.group:testinvalidpom:0.0.1-SNAPSHOT]' for com.example.group:testinvalidpom:0.0.1-SNAPSHOT is referencing itself.", - result.getFatals().get(0)); + assertThat(result.getFatals().get(0)).isEqualTo("'dependencies.dependency[com.example.group:testinvalidpom:0.0.1-SNAPSHOT]' for com.example.group:testinvalidpom:0.0.1-SNAPSHOT is referencing itself."); } @Test - void testSelfReferencingDependencyWithClassifierInRawModel() throws Exception { + void selfReferencingDependencyWithClassifierInRawModel() throws Exception { SimpleProblemCollector result = validateRaw("raw-model/self-referencing-classifier.xml"); assertViolations(result, 0, 0, 0); } @Test - void testCiFriendlySha1() throws Exception { + void ciFriendlySha1() throws Exception { SimpleProblemCollector result = validateRaw("raw-model/ok-ci-friendly-sha1.xml"); assertViolations(result, 0, 0, 0); } @Test - void testCiFriendlyRevision() throws Exception { + void ciFriendlyRevision() throws Exception { SimpleProblemCollector result = validateRaw("raw-model/ok-ci-friendly-revision.xml"); assertViolations(result, 0, 0, 0); } @Test - void testCiFriendlyChangeList() throws Exception { + void ciFriendlyChangeList() throws Exception { SimpleProblemCollector result = validateRaw("raw-model/ok-ci-friendly-changelist.xml"); assertViolations(result, 0, 0, 0); } @Test - void testCiFriendlyAllExpressions() throws Exception { + void ciFriendlyAllExpressions() throws Exception { SimpleProblemCollector result = validateRaw("raw-model/ok-ci-friendly-all-expressions.xml"); assertViolations(result, 0, 0, 0); } @Test - void testCiFriendlyBad() throws Exception { + void ciFriendlyBad() throws Exception { SimpleProblemCollector result = validateFile("raw-model/bad-ci-friendly.xml"); assertViolations(result, 0, 0, 1); - assertEquals( - "'version' contains an expression but should be a constant.", - result.getWarnings().get(0)); + assertThat(result.getWarnings().get(0)).isEqualTo("'version' contains an expression but should be a constant."); } @Test - void testCiFriendlyBadSha1Plus() throws Exception { + void ciFriendlyBadSha1Plus() throws Exception { SimpleProblemCollector result = validateFile("raw-model/bad-ci-friendly-sha1plus.xml"); assertViolations(result, 0, 0, 1); - assertEquals( - "'version' contains an expression but should be a constant.", - result.getWarnings().get(0)); + assertThat(result.getWarnings().get(0)).isEqualTo("'version' contains an expression but should be a constant."); } @Test - void testCiFriendlyBadSha1Plus2() throws Exception { + void ciFriendlyBadSha1Plus2() throws Exception { SimpleProblemCollector result = validateFile("raw-model/bad-ci-friendly-sha1plus2.xml"); assertViolations(result, 0, 0, 1); - assertEquals( - "'version' contains an expression but should be a constant.", - result.getWarnings().get(0)); + assertThat(result.getWarnings().get(0)).isEqualTo("'version' contains an expression but should be a constant."); } @Test - void testParentVersionLATEST() throws Exception { + void parentVersionLATEST() throws Exception { SimpleProblemCollector result = validateRaw("raw-model/bad-parent-version-latest.xml"); assertViolations(result, 0, 0, 1); - assertEquals( - "'parent.version' is either LATEST or RELEASE (both of them are being deprecated)", - result.getWarnings().get(0)); + assertThat(result.getWarnings().get(0)).isEqualTo("'parent.version' is either LATEST or RELEASE (both of them are being deprecated)"); } @Test - void testParentVersionRELEASE() throws Exception { + void parentVersionRELEASE() throws Exception { SimpleProblemCollector result = validateRaw("raw-model/bad-parent-version-release.xml"); assertViolations(result, 0, 0, 1); - assertEquals( - "'parent.version' is either LATEST or RELEASE (both of them are being deprecated)", - result.getWarnings().get(0)); + assertThat(result.getWarnings().get(0)).isEqualTo("'parent.version' is either LATEST or RELEASE (both of them are being deprecated)"); } @Test void repositoryWithExpression() throws Exception { SimpleProblemCollector result = validateFile("raw-model/repository-with-expression.xml"); assertViolations(result, 0, 1, 0); - assertEquals( - "'repositories.repository.[repo].url' contains an unsupported expression (only expressions starting with 'project.basedir' or 'project.rootDirectory' are supported).", - result.getErrors().get(0)); + assertThat(result.getErrors().get(0)).isEqualTo("'repositories.repository.[repo].url' contains an unsupported expression (only expressions starting with 'project.basedir' or 'project.rootDirectory' are supported)."); } @Test @@ -842,17 +792,13 @@ void profileActivationFileWithProjectExpression() throws Exception { SimpleProblemCollector result = validateFile("raw-model/profile-activation-file-with-project-expressions.xml"); assertViolations(result, 0, 0, 2); - assertEquals( - "'profiles.profile[exists-project-version].activation.file.exists' " - + "Failed to interpolate profile activation property ${project.version}/test.txt: " - + "${project.version} expressions are not supported during profile activation.", - result.getWarnings().get(0)); + assertThat(result.getWarnings().get(0)).isEqualTo("'profiles.profile[exists-project-version].activation.file.exists' " + + "Failed to interpolate profile activation property ${project.version}/test.txt: " + + "${project.version} expressions are not supported during profile activation."); - assertEquals( - "'profiles.profile[missing-project-version].activation.file.missing' " - + "Failed to interpolate profile activation property ${project.version}/test.txt: " - + "${project.version} expressions are not supported during profile activation.", - result.getWarnings().get(1)); + assertThat(result.getWarnings().get(1)).isEqualTo("'profiles.profile[missing-project-version].activation.file.missing' " + + "Failed to interpolate profile activation property ${project.version}/test.txt: " + + "${project.version} expressions are not supported during profile activation."); } @Test @@ -861,17 +807,13 @@ void profileActivationPropertyWithProjectExpression() throws Exception { validateFile("raw-model/profile-activation-property-with-project-expressions.xml"); assertViolations(result, 0, 0, 2); - assertEquals( - "'profiles.profile[property-name-project-version].activation.property.name' " - + "Failed to interpolate profile activation property ${project.version}: " - + "${project.version} expressions are not supported during profile activation.", - result.getWarnings().get(0)); - - assertEquals( - "'profiles.profile[property-value-project-version].activation.property.value' " - + "Failed to interpolate profile activation property ${project.version}: " - + "${project.version} expressions are not supported during profile activation.", - result.getWarnings().get(1)); + assertThat(result.getWarnings().get(0)).isEqualTo("'profiles.profile[property-name-project-version].activation.property.name' " + + "Failed to interpolate profile activation property ${project.version}: " + + "${project.version} expressions are not supported during profile activation."); + + assertThat(result.getWarnings().get(1)).isEqualTo("'profiles.profile[property-value-project-version].activation.property.value' " + + "Failed to interpolate profile activation property ${project.version}: " + + "${project.version} expressions are not supported during profile activation."); } @Test diff --git a/impl/maven-impl/src/test/java/org/apache/maven/impl/model/MavenBuildTimestampTest.java b/impl/maven-impl/src/test/java/org/apache/maven/impl/model/MavenBuildTimestampTest.java index ac3acae14a9a..9e4d67a59d93 100644 --- a/impl/maven-impl/src/test/java/org/apache/maven/impl/model/MavenBuildTimestampTest.java +++ b/impl/maven-impl/src/test/java/org/apache/maven/impl/model/MavenBuildTimestampTest.java @@ -24,15 +24,15 @@ import org.apache.maven.api.MonotonicClock; import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; class MavenBuildTimestampTest { @Test - void testMavenBuildTimestampUsesUTC() { + void mavenBuildTimestampUsesUTC() { Map interpolationProperties = new HashMap<>(); interpolationProperties.put("maven.build.timestamp.format", "yyyyMMdd'T'HHmm'Z'"); MavenBuildTimestamp timestamp = new MavenBuildTimestamp(MonotonicClock.now(), interpolationProperties); String formattedTimestamp = timestamp.formattedTimestamp(); - assertTrue(formattedTimestamp.endsWith("Z"), "We expect the UTC marker at the end of the timestamp."); + assertThat(formattedTimestamp.endsWith("Z")).as("We expect the UTC marker at the end of the timestamp.").isTrue(); } } diff --git a/impl/maven-impl/src/test/java/org/apache/maven/impl/model/MavenModelMergerTest.java b/impl/maven-impl/src/test/java/org/apache/maven/impl/model/MavenModelMergerTest.java index 22227f2da9f3..c07c164aca30 100644 --- a/impl/maven-impl/src/test/java/org/apache/maven/impl/model/MavenModelMergerTest.java +++ b/impl/maven-impl/src/test/java/org/apache/maven/impl/model/MavenModelMergerTest.java @@ -25,70 +25,69 @@ import org.apache.maven.api.model.Profile; import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNull; +import static org.assertj.core.api.Assertions.assertThat; class MavenModelMergerTest { private MavenModelMerger modelMerger = new MavenModelMerger(); // modelVersion is neither inherited nor injected @Test - void testMergeModelModelVersion() { + void mergeModelModelVersion() { Model parent = Model.newBuilder().modelVersion("4.0.0").build(); Model model = Model.newInstance(); Model.Builder builder = Model.newBuilder(model); modelMerger.mergeModel_ModelVersion(builder, model, parent, false, null); - assertNull(builder.build().getModelVersion()); + assertThat(builder.build().getModelVersion()).isNull(); model = Model.newBuilder().modelVersion("5.0.0").build(); builder = Model.newBuilder(model); modelMerger.mergeModel_ModelVersion(builder, model, parent, false, null); - assertEquals("5.0.0", builder.build().getModelVersion()); + assertThat(builder.build().getModelVersion()).isEqualTo("5.0.0"); } // ArtifactId is neither inherited nor injected @Test - void testMergeModelArtifactId() { + void mergeModelArtifactId() { Model parent = Model.newBuilder().artifactId("PARENT").build(); Model model = Model.newInstance(); Model.Builder builder = Model.newBuilder(model); modelMerger.mergeModel_ArtifactId(builder, model, parent, false, null); - assertNull(model.getArtifactId()); + assertThat(model.getArtifactId()).isNull(); model = Model.newBuilder().artifactId("MODEL").build(); builder = Model.newBuilder(model); modelMerger.mergeModel_ArtifactId(builder, model, parent, false, null); - assertEquals("MODEL", builder.build().getArtifactId()); + assertThat(builder.build().getArtifactId()).isEqualTo("MODEL"); } // Prerequisites are neither inherited nor injected @Test - void testMergeModelPrerequisites() { + void mergeModelPrerequisites() { Model parent = Model.newBuilder().prerequisites(Prerequisites.newInstance()).build(); Model model = Model.newInstance(); Model.Builder builder = Model.newBuilder(model); modelMerger.mergeModel_Prerequisites(builder, model, parent, false, null); - assertNull(builder.build().getPrerequisites()); + assertThat(builder.build().getPrerequisites()).isNull(); Prerequisites modelPrerequisites = Prerequisites.newBuilder().maven("3.0").build(); model = Model.newBuilder().prerequisites(modelPrerequisites).build(); builder = Model.newBuilder(model); modelMerger.mergeModel_Prerequisites(builder, model, parent, false, null); - assertEquals(modelPrerequisites, builder.build().getPrerequisites()); + assertThat(builder.build().getPrerequisites()).isEqualTo(modelPrerequisites); } // Profiles are neither inherited nor injected @Test - void testMergeModelProfiles() { + void mergeModelProfiles() { Model parent = Model.newBuilder() .profiles(Collections.singletonList(Profile.newInstance())) .build(); Model model = Model.newInstance(); Model.Builder builder = Model.newBuilder(model); modelMerger.mergeModel_Profiles(builder, model, parent, false, null); - assertEquals(0, builder.build().getProfiles().size()); + assertThat(builder.build().getProfiles().size()).isEqualTo(0); Profile modelProfile = Profile.newBuilder().id("MODEL").build(); model = Model.newBuilder() @@ -96,6 +95,6 @@ void testMergeModelProfiles() { .build(); builder = Model.newBuilder(model); modelMerger.mergeModel_Prerequisites(builder, model, parent, false, null); - assertEquals(Collections.singletonList(modelProfile), builder.build().getProfiles()); + assertThat(builder.build().getProfiles()).isEqualTo(Collections.singletonList(modelProfile)); } } diff --git a/impl/maven-impl/src/test/java/org/apache/maven/impl/model/profile/AbstractProfileActivatorTest.java b/impl/maven-impl/src/test/java/org/apache/maven/impl/model/profile/AbstractProfileActivatorTest.java index 3829f03e49ad..edf6e5406cae 100644 --- a/impl/maven-impl/src/test/java/org/apache/maven/impl/model/profile/AbstractProfileActivatorTest.java +++ b/impl/maven-impl/src/test/java/org/apache/maven/impl/model/profile/AbstractProfileActivatorTest.java @@ -32,7 +32,7 @@ import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; -import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Provides common services to test {@link ProfileActivator} implementations. @@ -74,8 +74,8 @@ protected void assertActivation(boolean active, Profile profile, ProfileActivati SimpleProblemCollector problems = new SimpleProblemCollector(); boolean res = activator.isActive(profile, context, problems); - assertEquals(0, problems.getErrors().size(), problems.getErrors().toString()); - assertEquals(0, problems.getWarnings().size(), problems.getWarnings().toString()); - assertEquals(active, res); + assertThat(problems.getErrors().size()).as(problems.getErrors().toString()).isEqualTo(0); + assertThat(problems.getWarnings().size()).as(problems.getWarnings().toString()).isEqualTo(0); + assertThat(res).isEqualTo(active); } } diff --git a/impl/maven-impl/src/test/java/org/apache/maven/impl/model/profile/ConditionParserTest.java b/impl/maven-impl/src/test/java/org/apache/maven/impl/model/profile/ConditionParserTest.java index 56d2cbb3aec9..757fdbded139 100644 --- a/impl/maven-impl/src/test/java/org/apache/maven/impl/model/profile/ConditionParserTest.java +++ b/impl/maven-impl/src/test/java/org/apache/maven/impl/model/profile/ConditionParserTest.java @@ -33,11 +33,10 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.within; +import static org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; class ConditionParserTest { ConditionParser parser; @@ -71,117 +70,111 @@ private ProfileActivationContext createMockContext() { } @Test - void testStringLiterals() { - assertEquals("Hello, World!", parser.parse("'Hello, World!'")); - assertEquals("Hello, World!", parser.parse("\"Hello, World!\"")); + void stringLiterals() { + assertThat(parser.parse("'Hello, World!'")).isEqualTo("Hello, World!"); + assertThat(parser.parse("\"Hello, World!\"")).isEqualTo("Hello, World!"); } @Test - void testStringConcatenation() { - assertEquals("HelloWorld", parser.parse("'Hello' + 'World'")); - assertEquals("Hello123", parser.parse("'Hello' + 123")); + void stringConcatenation() { + assertThat(parser.parse("'Hello' + 'World'")).isEqualTo("HelloWorld"); + assertThat(parser.parse("'Hello' + 123")).isEqualTo("Hello123"); } @Test - void testLengthFunction() { - assertEquals(13, parser.parse("length('Hello, World!')")); - assertEquals(5, parser.parse("length(\"Hello\")")); + void lengthFunction() { + assertThat(parser.parse("length('Hello, World!')")).isEqualTo(13); + assertThat(parser.parse("length(\"Hello\")")).isEqualTo(5); } @Test - void testCaseConversionFunctions() { - assertEquals("HELLO", parser.parse("upper('hello')")); - assertEquals("world", parser.parse("lower('WORLD')")); + void caseConversionFunctions() { + assertThat(parser.parse("upper('hello')")).isEqualTo("HELLO"); + assertThat(parser.parse("lower('WORLD')")).isEqualTo("world"); } @Test - void testConcatFunction() { - assertEquals("HelloWorld", parser.parse("'Hello' + 'World'")); - assertEquals("The answer is 42", parser.parse("'The answer is ' + 42")); - assertEquals("The answer is 42", parser.parse("'The answer is ' + 42.0")); - assertEquals("The answer is 42", parser.parse("'The answer is ' + 42.0f")); - assertEquals("Pi is approximately 3.14", parser.parse("'Pi is approximately ' + 3.14")); - assertEquals("Pi is approximately 3.14", parser.parse("'Pi is approximately ' + 3.14f")); + void concatFunction() { + assertThat(parser.parse("'Hello' + 'World'")).isEqualTo("HelloWorld"); + assertThat(parser.parse("'The answer is ' + 42")).isEqualTo("The answer is 42"); + assertThat(parser.parse("'The answer is ' + 42.0")).isEqualTo("The answer is 42"); + assertThat(parser.parse("'The answer is ' + 42.0f")).isEqualTo("The answer is 42"); + assertThat(parser.parse("'Pi is approximately ' + 3.14")).isEqualTo("Pi is approximately 3.14"); + assertThat(parser.parse("'Pi is approximately ' + 3.14f")).isEqualTo("Pi is approximately 3.14"); } @Test void testToString() { - assertEquals("42", ConditionParser.toString(42)); - assertEquals("42", ConditionParser.toString(42L)); - assertEquals("42", ConditionParser.toString(42.0)); - assertEquals("42", ConditionParser.toString(42.0f)); - assertEquals("3.14", ConditionParser.toString(3.14)); - assertEquals("3.14", ConditionParser.toString(3.14f)); - assertEquals("true", ConditionParser.toString(true)); - assertEquals("false", ConditionParser.toString(false)); - assertEquals("hello", ConditionParser.toString("hello")); + assertThat(ConditionParser.toString(42)).isEqualTo("42"); + assertThat(ConditionParser.toString(42L)).isEqualTo("42"); + assertThat(ConditionParser.toString(42.0)).isEqualTo("42"); + assertThat(ConditionParser.toString(42.0f)).isEqualTo("42"); + assertThat(ConditionParser.toString(3.14)).isEqualTo("3.14"); + assertThat(ConditionParser.toString(3.14f)).isEqualTo("3.14"); + assertThat(ConditionParser.toString(true)).isEqualTo("true"); + assertThat(ConditionParser.toString(false)).isEqualTo("false"); + assertThat(ConditionParser.toString("hello")).isEqualTo("hello"); } @Test - void testSubstringFunction() { - assertEquals("World", parser.parse("substring('Hello, World!', 7, 12)")); - assertEquals("World!", parser.parse("substring('Hello, World!', 7)")); + void substringFunction() { + assertThat(parser.parse("substring('Hello, World!', 7, 12)")).isEqualTo("World"); + assertThat(parser.parse("substring('Hello, World!', 7)")).isEqualTo("World!"); } @Test - void testIndexOf() { - assertEquals(7, parser.parse("indexOf('Hello, World!', 'World')")); - assertEquals(-1, parser.parse("indexOf('Hello, World!', 'OpenAI')")); + void indexOf() { + assertThat(parser.parse("indexOf('Hello, World!', 'World')")).isEqualTo(7); + assertThat(parser.parse("indexOf('Hello, World!', 'OpenAI')")).isEqualTo(-1); } @Test - void testInRange() { - assertTrue((Boolean) parser.parse("inrange('1.8.0_292', '[1.8,2.0)')")); - assertFalse((Boolean) parser.parse("inrange('1.7.0', '[1.8,2.0)')")); + void inRange() { + assertThat((Boolean) parser.parse("inrange('1.8.0_292', '[1.8,2.0)')")).isTrue(); + assertThat((Boolean) parser.parse("inrange('1.7.0', '[1.8,2.0)')")).isFalse(); } @Test - void testIfFunction() { - assertEquals("long", parser.parse("if(length('test') > 3, 'long', 'short')")); - assertEquals("short", parser.parse("if(length('hi') > 3, 'long', 'short')")); + void ifFunction() { + assertThat(parser.parse("if(length('test') > 3, 'long', 'short')")).isEqualTo("long"); + assertThat(parser.parse("if(length('hi') > 3, 'long', 'short')")).isEqualTo("short"); } @Test - void testContainsFunction() { - assertTrue((Boolean) parser.parse("contains('Hello, World!', 'World')")); - assertFalse((Boolean) parser.parse("contains('Hello, World!', 'OpenAI')")); + void containsFunction() { + assertThat((Boolean) parser.parse("contains('Hello, World!', 'World')")).isTrue(); + assertThat((Boolean) parser.parse("contains('Hello, World!', 'OpenAI')")).isFalse(); } @Test - void testMatchesFunction() { - assertTrue((Boolean) parser.parse("matches('test123', '\\w+')")); - assertFalse((Boolean) parser.parse("matches('test123', '\\d+')")); + void matchesFunction() { + assertThat((Boolean) parser.parse("matches('test123', '\\w+')")).isTrue(); + assertThat((Boolean) parser.parse("matches('test123', '\\d+')")).isFalse(); } @Test - void testComplexExpression() { + void complexExpression() { String expression = "if(contains(lower('HELLO WORLD'), 'hello'), upper('success') + '!', 'failure')"; - assertEquals("SUCCESS!", parser.parse(expression)); + assertThat(parser.parse(expression)).isEqualTo("SUCCESS!"); } @Test - void testStringComparison() { - assertTrue((Boolean) parser.parse("'abc' != 'cdf'")); - assertFalse((Boolean) parser.parse("'abc' != 'abc'")); - assertTrue((Boolean) parser.parse("'abc' == 'abc'")); - assertFalse((Boolean) parser.parse("'abc' == 'cdf'")); + void stringComparison() { + assertThat((Boolean) parser.parse("'abc' != 'cdf'")).isTrue(); + assertThat((Boolean) parser.parse("'abc' != 'abc'")).isFalse(); + assertThat((Boolean) parser.parse("'abc' == 'abc'")).isTrue(); + assertThat((Boolean) parser.parse("'abc' == 'cdf'")).isFalse(); } @Test - void testParenthesesMismatch() { + void parenthesesMismatch() { functions.put("property", args -> "foo"); functions.put("inrange", args -> false); - assertThrows( - RuntimeException.class, - () -> parser.parse( - "property('os.name') == 'windows' && property('os.arch') != 'amd64') && inrange(property('os.version'), '[99,)')"), - "Should throw RuntimeException due to parentheses mismatch"); + assertThatExceptionOfType(RuntimeException.class).as("Should throw RuntimeException due to parentheses mismatch").isThrownBy(() -> parser.parse( + "property('os.name') == 'windows' && property('os.arch') != 'amd64') && inrange(property('os.version'), '[99,)')")); - assertThrows( - RuntimeException.class, - () -> parser.parse( - "(property('os.name') == 'windows' && property('os.arch') != 'amd64') && inrange(property('os.version'), '[99,)'"), - "Should throw RuntimeException due to parentheses mismatch"); + assertThatExceptionOfType(RuntimeException.class).as("Should throw RuntimeException due to parentheses mismatch").isThrownBy(() -> parser.parse( + "(property('os.name') == 'windows' && property('os.arch') != 'amd64') && inrange(property('os.version'), '[99,)'")); // This should not throw an exception if parentheses are balanced and properties are handled correctly assertDoesNotThrow( @@ -190,80 +183,80 @@ void testParenthesesMismatch() { } @Test - void testBasicArithmetic() { - assertEquals(5.0, parser.parse("2 + 3")); - assertEquals(10.0, parser.parse("15 - 5")); - assertEquals(24.0, parser.parse("6 * 4")); - assertEquals(3.0, parser.parse("9 / 3")); + void basicArithmetic() { + assertThat(parser.parse("2 + 3")).isEqualTo(5.0); + assertThat(parser.parse("15 - 5")).isEqualTo(10.0); + assertThat(parser.parse("6 * 4")).isEqualTo(24.0); + assertThat(parser.parse("9 / 3")).isEqualTo(3.0); } @Test - void testArithmeticPrecedence() { - assertEquals(14.0, parser.parse("2 + 3 * 4")); - assertEquals(20.0, parser.parse("(2 + 3) * 4")); - assertEquals(11.0, parser.parse("15 - 6 + 2")); - assertEquals(10.0, parser.parse("10 / 2 + 2 * 2.5")); + void arithmeticPrecedence() { + assertThat(parser.parse("2 + 3 * 4")).isEqualTo(14.0); + assertThat(parser.parse("(2 + 3) * 4")).isEqualTo(20.0); + assertThat(parser.parse("15 - 6 + 2")).isEqualTo(11.0); + assertThat(parser.parse("10 / 2 + 2 * 2.5")).isEqualTo(10.0); } @Test - void testFloatingPointArithmetic() { - assertEquals(5.5, parser.parse("2.2 + 3.3")); - assertEquals(0.1, (Double) parser.parse("3.3 - 3.2"), 1e-10); - assertEquals(6.25, parser.parse("2.5 * 2.5")); - assertEquals(2.5, parser.parse("5 / 2")); + void floatingPointArithmetic() { + assertThat(parser.parse("2.2 + 3.3")).isEqualTo(5.5); + assertThat((Double) parser.parse("3.3 - 3.2")).isCloseTo(0.1, within(1e-10)); + assertThat(parser.parse("2.5 * 2.5")).isEqualTo(6.25); + assertThat(parser.parse("5 / 2")).isEqualTo(2.5); } @Test - void testArithmeticComparisons() { - assertTrue((Boolean) parser.parse("5 > 3")); - assertTrue((Boolean) parser.parse("3 < 5")); - assertTrue((Boolean) parser.parse("5 >= 5")); - assertTrue((Boolean) parser.parse("3 <= 3")); - assertTrue((Boolean) parser.parse("5 == 5")); - assertTrue((Boolean) parser.parse("5 != 3")); - assertFalse((Boolean) parser.parse("5 < 3")); - assertFalse((Boolean) parser.parse("3 > 5")); - assertFalse((Boolean) parser.parse("5 != 5")); + void arithmeticComparisons() { + assertThat((Boolean) parser.parse("5 > 3")).isTrue(); + assertThat((Boolean) parser.parse("3 < 5")).isTrue(); + assertThat((Boolean) parser.parse("5 >= 5")).isTrue(); + assertThat((Boolean) parser.parse("3 <= 3")).isTrue(); + assertThat((Boolean) parser.parse("5 == 5")).isTrue(); + assertThat((Boolean) parser.parse("5 != 3")).isTrue(); + assertThat((Boolean) parser.parse("5 < 3")).isFalse(); + assertThat((Boolean) parser.parse("3 > 5")).isFalse(); + assertThat((Boolean) parser.parse("5 != 5")).isFalse(); } @Test - void testComplexArithmeticExpressions() { - assertFalse((Boolean) parser.parse("(2 + 3 * 4) > (10 + 5)")); - assertTrue((Boolean) parser.parse("(2 + 3 * 4) < (10 + 5)")); - assertTrue((Boolean) parser.parse("(10 / 2 + 3) == 8")); - assertTrue((Boolean) parser.parse("(10 / 2 + 3) != 9")); + void complexArithmeticExpressions() { + assertThat((Boolean) parser.parse("(2 + 3 * 4) > (10 + 5)")).isFalse(); + assertThat((Boolean) parser.parse("(2 + 3 * 4) < (10 + 5)")).isTrue(); + assertThat((Boolean) parser.parse("(10 / 2 + 3) == 8")).isTrue(); + assertThat((Boolean) parser.parse("(10 / 2 + 3) != 9")).isTrue(); } @Test - void testArithmeticFunctions() { - assertEquals(5.0, parser.parse("2 + 3")); - assertEquals(2.0, parser.parse("5 - 3")); - assertEquals(15.0, parser.parse("3 * 5")); - assertEquals(2.5, parser.parse("5 / 2")); + void arithmeticFunctions() { + assertThat(parser.parse("2 + 3")).isEqualTo(5.0); + assertThat(parser.parse("5 - 3")).isEqualTo(2.0); + assertThat(parser.parse("3 * 5")).isEqualTo(15.0); + assertThat(parser.parse("5 / 2")).isEqualTo(2.5); } @Test - void testCombinedArithmeticAndLogic() { - assertTrue((Boolean) parser.parse("(5 > 3) && (10 / 2 == 5)")); - assertFalse((Boolean) parser.parse("(5 < 3) || (10 / 2 != 5)")); - assertTrue((Boolean) parser.parse("2 + 3 == 1 * 5")); + void combinedArithmeticAndLogic() { + assertThat((Boolean) parser.parse("(5 > 3) && (10 / 2 == 5)")).isTrue(); + assertThat((Boolean) parser.parse("(5 < 3) || (10 / 2 != 5)")).isFalse(); + assertThat((Boolean) parser.parse("2 + 3 == 1 * 5")).isTrue(); } @Test - void testDivisionByZero() { - assertThrows(ArithmeticException.class, () -> parser.parse("5 / 0")); + void divisionByZero() { + assertThatExceptionOfType(ArithmeticException.class).isThrownBy(() -> parser.parse("5 / 0")); } @Test - void testPropertyAlias() { - assertTrue((Boolean) parser.parse("${os.name} == 'windows'")); - assertFalse((Boolean) parser.parse("${os.name} == 'linux'")); - assertTrue((Boolean) parser.parse("${os.arch} == 'amd64' && ${os.name} == 'windows'")); - assertThrows(RuntimeException.class, () -> parser.parse("${unclosed")); + void propertyAlias() { + assertThat((Boolean) parser.parse("${os.name} == 'windows'")).isTrue(); + assertThat((Boolean) parser.parse("${os.name} == 'linux'")).isFalse(); + assertThat((Boolean) parser.parse("${os.arch} == 'amd64' && ${os.name} == 'windows'")).isTrue(); + assertThatExceptionOfType(RuntimeException.class).isThrownBy(() -> parser.parse("${unclosed")); } @Test - void testNestedPropertyAlias() { + void nestedPropertyAlias() { functions.put("property", args -> { if (args.get(0).equals("project.rootDirectory")) { return "/home/user/project"; @@ -273,27 +266,27 @@ void testNestedPropertyAlias() { functions.put("exists", args -> true); // Mock implementation Object result = parser.parse("exists('${project.rootDirectory}/someFile.txt')"); - assertTrue((Boolean) result); + assertThat((Boolean) result).isTrue(); result = parser.parse("exists('${project.rootDirectory}/${nested.property}/someFile.txt')"); - assertTrue((Boolean) result); + assertThat((Boolean) result).isTrue(); assertDoesNotThrow(() -> parser.parse("property('')")); } @Test - void testToInt() { - assertEquals(123, ConditionParser.toInt(123)); - assertEquals(123, ConditionParser.toInt(123L)); - assertEquals(123, ConditionParser.toInt(123.0)); - assertEquals(123, ConditionParser.toInt(123.5)); // This will truncate the decimal part - assertEquals(123, ConditionParser.toInt("123")); - assertEquals(123, ConditionParser.toInt("123.0")); - assertEquals(123, ConditionParser.toInt("123.5")); // This will truncate the decimal part - assertEquals(1, ConditionParser.toInt(true)); - assertEquals(0, ConditionParser.toInt(false)); - - assertThrows(RuntimeException.class, () -> ConditionParser.toInt("not a number")); - assertThrows(RuntimeException.class, () -> ConditionParser.toInt(new Object())); + void toInt() { + assertThat(ConditionParser.toInt(123)).isEqualTo(123); + assertThat(ConditionParser.toInt(123L)).isEqualTo(123); + assertThat(ConditionParser.toInt(123.0)).isEqualTo(123); + assertThat(ConditionParser.toInt(123.5)).isEqualTo(123); // This will truncate the decimal part + assertThat(ConditionParser.toInt("123")).isEqualTo(123); + assertThat(ConditionParser.toInt("123.0")).isEqualTo(123); + assertThat(ConditionParser.toInt("123.5")).isEqualTo(123); // This will truncate the decimal part + assertThat(ConditionParser.toInt(true)).isEqualTo(1); + assertThat(ConditionParser.toInt(false)).isEqualTo(0); + + assertThatExceptionOfType(RuntimeException.class).isThrownBy(() -> ConditionParser.toInt("not a number")); + assertThatExceptionOfType(RuntimeException.class).isThrownBy(() -> ConditionParser.toInt(new Object())); } } diff --git a/impl/maven-impl/src/test/java/org/apache/maven/impl/model/profile/ConditionProfileActivatorTest.java b/impl/maven-impl/src/test/java/org/apache/maven/impl/model/profile/ConditionProfileActivatorTest.java index 5d371c2fc3cc..890c5350322c 100644 --- a/impl/maven-impl/src/test/java/org/apache/maven/impl/model/profile/ConditionProfileActivatorTest.java +++ b/impl/maven-impl/src/test/java/org/apache/maven/impl/model/profile/ConditionProfileActivatorTest.java @@ -39,12 +39,10 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType; -public class ConditionProfileActivatorTest extends AbstractProfileActivatorTest { +class ConditionProfileActivatorTest extends AbstractProfileActivatorTest { @TempDir Path tempDir; @@ -75,7 +73,7 @@ private Map newJdkProperties(String javaVersion) { } @Test - void testNullSafe() throws Exception { + void nullSafe() throws Exception { Profile p = Profile.newInstance(); assertActivation(false, p, newContext(null, null)); @@ -86,7 +84,7 @@ void testNullSafe() throws Exception { } @Test - void testJdkPrefix() throws Exception { + void jdkPrefix() throws Exception { Profile profile = newProfile("inrange(${java.version}, '[1.4,1.5)')"); assertActivation(true, profile, newContext(null, newJdkProperties("1.4"))); @@ -100,7 +98,7 @@ void testJdkPrefix() throws Exception { } @Test - void testJdkPrefixNegated() throws Exception { + void jdkPrefixNegated() throws Exception { Profile profile = newProfile("not(inrange(${java.version}, '[1.4,1.5)'))"); assertActivation(false, profile, newContext(null, newJdkProperties("1.4"))); @@ -114,7 +112,7 @@ void testJdkPrefixNegated() throws Exception { } @Test - void testJdkVersionRangeInclusiveBounds() throws Exception { + void jdkVersionRangeInclusiveBounds() throws Exception { Profile profile = newProfile("inrange(${java.version}, '[1.5,1.6.1]')"); assertActivation(false, profile, newContext(null, newJdkProperties("1.4"))); @@ -135,7 +133,7 @@ void testJdkVersionRangeInclusiveBounds() throws Exception { } @Test - void testJdkVersionRangeExclusiveBounds() throws Exception { + void jdkVersionRangeExclusiveBounds() throws Exception { Profile profile = newProfile("inrange(${java.version}, '[1.3.1,1.6)')"); assertActivation(false, profile, newContext(null, newJdkProperties("1.3"))); @@ -157,7 +155,7 @@ void testJdkVersionRangeExclusiveBounds() throws Exception { } @Test - void testJdkVersionRangeInclusiveLowerBound() throws Exception { + void jdkVersionRangeInclusiveLowerBound() throws Exception { Profile profile = newProfile("inrange(${java.version}, '[1.5,)')"); assertActivation(false, profile, newContext(null, newJdkProperties("1.4"))); @@ -178,7 +176,7 @@ void testJdkVersionRangeInclusiveLowerBound() throws Exception { } @Test - void testJdkVersionRangeExclusiveUpperBound() throws Exception { + void jdkVersionRangeExclusiveUpperBound() throws Exception { Profile profile = newProfile("inrange(${java.version}, '(,1.6)')"); assertActivation(true, profile, newContext(null, newJdkProperties("1.5"))); @@ -195,7 +193,7 @@ void testJdkVersionRangeExclusiveUpperBound() throws Exception { @Disabled @Test - void testJdkRubbishJavaVersion() { + void jdkRubbishJavaVersion() { Profile profile = newProfile("inrange(${java.version}, '[1.8,)')"); assertActivationWithProblems(profile, newContext(null, newJdkProperties("Pūteketeke")), "invalid JDK version"); @@ -208,13 +206,11 @@ private void assertActivationWithProblems( Profile profile, ProfileActivationContext context, String warningContains) { SimpleProblemCollector problems = new SimpleProblemCollector(); - assertFalse(activator.isActive(profile, context, problems)); + assertThat(activator.isActive(profile, context, problems)).isFalse(); - assertEquals(0, problems.getErrors().size(), problems.getErrors().toString()); - assertEquals(1, problems.getWarnings().size(), problems.getWarnings().toString()); - assertTrue( - problems.getWarnings().get(0).contains(warningContains), - problems.getWarnings().toString()); + assertThat(problems.getErrors().size()).as(problems.getErrors().toString()).isEqualTo(0); + assertThat(problems.getWarnings().size()).as(problems.getWarnings().toString()).isEqualTo(1); + assertThat(problems.getWarnings().get(0).contains(warningContains)).as(problems.getWarnings().toString()).isTrue(); } private Map newOsProperties(String osName, String osVersion, String osArch) { @@ -222,7 +218,7 @@ private Map newOsProperties(String osName, String osVersion, Str } @Test - void testOsVersionStringComparison() throws Exception { + void osVersionStringComparison() throws Exception { Profile profile = newProfile("inrange(${os.version}, '[6.5.0-1014-aws,6.6)')"); assertActivation(true, profile, newContext(null, newOsProperties("linux", "6.5.0-1014-aws", "amd64"))); @@ -232,7 +228,7 @@ void testOsVersionStringComparison() throws Exception { } @Test - void testOsVersionRegexMatching() throws Exception { + void osVersionRegexMatching() throws Exception { Profile profile = newProfile("matches(${os.version}, '.*aws')"); assertActivation(true, profile, newContext(null, newOsProperties("linux", "6.5.0-1014-aws", "amd64"))); @@ -242,7 +238,7 @@ void testOsVersionRegexMatching() throws Exception { } @Test - void testOsName() { + void osName() { Profile profile = newProfile("${os.name} == 'windows'"); assertActivation(false, profile, newContext(null, newOsProperties("linux", "6.5.0-1014-aws", "amd64"))); @@ -250,7 +246,7 @@ void testOsName() { } @Test - void testOsNegatedName() { + void osNegatedName() { Profile profile = newProfile("${os.name} != 'windows'"); assertActivation(true, profile, newContext(null, newOsProperties("linux", "6.5.0-1014-aws", "amd64"))); @@ -258,7 +254,7 @@ void testOsNegatedName() { } @Test - void testOsArch() { + void osArch() { Profile profile = newProfile("${os.arch} == 'amd64'"); assertActivation(true, profile, newContext(null, newOsProperties("linux", "6.5.0-1014-aws", "amd64"))); @@ -266,7 +262,7 @@ void testOsArch() { } @Test - void testOsNegatedArch() { + void osNegatedArch() { Profile profile = newProfile("${os.arch} != 'amd64'"); assertActivation(false, profile, newContext(null, newOsProperties("linux", "6.5.0-1014-aws", "amd64"))); @@ -274,7 +270,7 @@ void testOsNegatedArch() { } @Test - void testOsAllConditions() { + void osAllConditions() { Profile profile = newProfile("${os.name} == 'windows' && ${os.arch} != 'amd64' && inrange(${os.version}, '[99,)')"); @@ -285,7 +281,7 @@ void testOsAllConditions() { } @Test - public void testOsCapitalName() { + void osCapitalName() { Profile profile = newProfile("lower(${os.name}) == 'mac os x'"); assertActivation(false, profile, newContext(null, newOsProperties("linux", "6.5.0-1014-aws", "amd64"))); @@ -299,7 +295,7 @@ private Map newPropProperties(String key, String value) { } @Test - void testPropWithNameOnlyUserProperty() throws Exception { + void propWithNameOnlyUserProperty() throws Exception { Profile profile = newProfile("${prop}"); assertActivation(true, profile, newContext(newPropProperties("prop", "value"), null)); @@ -308,7 +304,7 @@ void testPropWithNameOnlyUserProperty() throws Exception { } @Test - void testPropWithNameOnlySystemProperty() throws Exception { + void propWithNameOnlySystemProperty() throws Exception { Profile profile = newProfile("${prop}"); assertActivation(true, profile, newContext(null, newPropProperties("prop", "value"))); @@ -317,7 +313,7 @@ void testPropWithNameOnlySystemProperty() throws Exception { } @Test - void testPropWithNegatedNameOnlyUserProperty() throws Exception { + void propWithNegatedNameOnlyUserProperty() throws Exception { Profile profile = newProfile("not(${prop})"); assertActivation(false, profile, newContext(newPropProperties("prop", "value"), null)); @@ -326,7 +322,7 @@ void testPropWithNegatedNameOnlyUserProperty() throws Exception { } @Test - void testPropWithNegatedNameOnlySystemProperty() throws Exception { + void propWithNegatedNameOnlySystemProperty() throws Exception { Profile profile = newProfile("not(${prop})"); assertActivation(false, profile, newContext(null, newPropProperties("prop", "value"))); @@ -335,7 +331,7 @@ void testPropWithNegatedNameOnlySystemProperty() throws Exception { } @Test - void testPropWithValueUserProperty() throws Exception { + void propWithValueUserProperty() throws Exception { Profile profile = newProfile("${prop} == 'value'"); assertActivation(true, profile, newContext(newPropProperties("prop", "value"), null)); @@ -344,7 +340,7 @@ void testPropWithValueUserProperty() throws Exception { } @Test - void testPropWithValueSystemProperty() throws Exception { + void propWithValueSystemProperty() throws Exception { Profile profile = newProfile("${prop} == 'value'"); assertActivation(true, profile, newContext(null, newPropProperties("prop", "value"))); @@ -353,7 +349,7 @@ void testPropWithValueSystemProperty() throws Exception { } @Test - void testPropWithNegatedValueUserProperty() throws Exception { + void propWithNegatedValueUserProperty() throws Exception { Profile profile = newProfile("${prop} != 'value'"); assertActivation(false, profile, newContext(newPropProperties("prop", "value"), null)); @@ -362,7 +358,7 @@ void testPropWithNegatedValueUserProperty() throws Exception { } @Test - void testPropWithNegatedValueSystemProperty() throws Exception { + void propWithNegatedValueSystemProperty() throws Exception { Profile profile = newProfile("${prop} != 'value'"); assertActivation(false, profile, newContext(null, newPropProperties("prop", "value"))); @@ -371,7 +367,7 @@ void testPropWithNegatedValueSystemProperty() throws Exception { } @Test - void testPropWithValueUserPropertyDominantOverSystemProperty() throws Exception { + void propWithValueUserPropertyDominantOverSystemProperty() throws Exception { Profile profile = newProfile("${prop} == 'value'"); Map props1 = newPropProperties("prop", "value"); @@ -383,15 +379,13 @@ void testPropWithValueUserPropertyDominantOverSystemProperty() throws Exception @Test @Disabled - void testFileRootDirectoryWithNull() { - IllegalStateException e = assertThrows( - IllegalStateException.class, - () -> assertActivation(false, newProfile("exists('${project.rootDirectory}')"), newFileContext(null))); - assertEquals(RootLocator.UNABLE_TO_FIND_ROOT_PROJECT_MESSAGE, e.getMessage()); + void fileRootDirectoryWithNull() { + IllegalStateException e = assertThatExceptionOfType(IllegalStateException.class).isThrownBy(() -> assertActivation(false, newProfile("exists('${project.rootDirectory}')"), newFileContext(null))).actual(); + assertThat(e.getMessage()).isEqualTo(RootLocator.UNABLE_TO_FIND_ROOT_PROJECT_MESSAGE); } @Test - void testFileRootDirectory() { + void fileRootDirectory() { assertActivation(false, newProfile("exists('${project.rootDirectory}/someFile.txt')"), newFileContext()); assertActivation(true, newProfile("missing('${project.rootDirectory}/someFile.txt')"), newFileContext()); assertActivation(true, newProfile("exists('${project.rootDirectory}')"), newFileContext()); @@ -402,7 +396,7 @@ void testFileRootDirectory() { @Test @Disabled - void testFileWilcards() { + void fileWilcards() { assertActivation(true, newProfile("exists('${project.rootDirectory}/**/*.xsd')"), newFileContext()); assertActivation(true, newProfile("exists('${project.basedir}/**/*.xsd')"), newFileContext()); assertActivation(true, newProfile("exists('${project.basedir}/**/*.xsd')"), newFileContext()); @@ -411,7 +405,7 @@ void testFileWilcards() { } @Test - void testFileIsActiveNoFileWithShortBasedir() { + void fileIsActiveNoFileWithShortBasedir() { assertActivation(false, newExistsProfile(null), newFileContext()); assertActivation(false, newProfile("exists('someFile.txt')"), newFileContext()); assertActivation(false, newProfile("exists('${basedir}/someFile.txt')"), newFileContext()); @@ -422,7 +416,7 @@ void testFileIsActiveNoFileWithShortBasedir() { } @Test - void testFileIsActiveNoFile() { + void fileIsActiveNoFile() { assertActivation(false, newExistsProfile(null), newFileContext()); assertActivation(false, newProfile("exists('someFile.txt')"), newFileContext()); assertActivation(false, newProfile("exists('${project.basedir}/someFile.txt')"), newFileContext()); @@ -433,7 +427,7 @@ void testFileIsActiveNoFile() { } @Test - void testFileIsActiveExistsFileExists() { + void fileIsActiveExistsFileExists() { assertActivation(true, newProfile("exists('file.txt')"), newFileContext()); assertActivation(true, newProfile("exists('${project.basedir}')"), newFileContext()); assertActivation(true, newProfile("exists('${project.basedir}/file.txt')"), newFileContext()); diff --git a/impl/maven-impl/src/test/java/org/apache/maven/impl/model/profile/FileProfileActivatorTest.java b/impl/maven-impl/src/test/java/org/apache/maven/impl/model/profile/FileProfileActivatorTest.java index c7312beb66d2..c0406ac0f6b4 100644 --- a/impl/maven-impl/src/test/java/org/apache/maven/impl/model/profile/FileProfileActivatorTest.java +++ b/impl/maven-impl/src/test/java/org/apache/maven/impl/model/profile/FileProfileActivatorTest.java @@ -32,8 +32,8 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType; /** * Tests {@link FileProfileActivator}. @@ -60,17 +60,15 @@ void setUp() throws Exception { } @Test - void testRootDirectoryWithNull() { + void rootDirectoryWithNull() { context.setModel(Model.newInstance()); - NullPointerException e = assertThrows( - NullPointerException.class, - () -> assertActivation(false, newExistsProfile("${project.rootDirectory}"), context)); - assertEquals(RootLocator.UNABLE_TO_FIND_ROOT_PROJECT_MESSAGE, e.getMessage()); + NullPointerException e = assertThatExceptionOfType(NullPointerException.class).isThrownBy(() -> assertActivation(false, newExistsProfile("${project.rootDirectory}"), context)).actual(); + assertThat(e.getMessage()).isEqualTo(RootLocator.UNABLE_TO_FIND_ROOT_PROJECT_MESSAGE); } @Test - void testRootDirectory() { + void rootDirectory() { assertActivation(false, newExistsProfile("${project.rootDirectory}/someFile.txt"), context); assertActivation(true, newMissingProfile("${project.rootDirectory}/someFile.txt"), context); assertActivation(true, newExistsProfile("${project.rootDirectory}"), context); @@ -80,7 +78,7 @@ void testRootDirectory() { } @Test - void testIsActiveNoFileWithShortBasedir() { + void isActiveNoFileWithShortBasedir() { assertActivation(false, newExistsProfile(null), context); assertActivation(false, newExistsProfile("someFile.txt"), context); assertActivation(false, newExistsProfile("${basedir}/someFile.txt"), context); @@ -91,7 +89,7 @@ void testIsActiveNoFileWithShortBasedir() { } @Test - void testIsActiveNoFile() { + void isActiveNoFile() { assertActivation(false, newExistsProfile(null), context); assertActivation(false, newExistsProfile("someFile.txt"), context); assertActivation(false, newExistsProfile("${project.basedir}/someFile.txt"), context); @@ -102,7 +100,7 @@ void testIsActiveNoFile() { } @Test - void testIsActiveExistsFileExists() { + void isActiveExistsFileExists() { assertActivation(true, newExistsProfile("file.txt"), context); assertActivation(true, newExistsProfile("${project.basedir}"), context); assertActivation(true, newExistsProfile("${project.basedir}/" + "file.txt"), context); @@ -113,13 +111,13 @@ void testIsActiveExistsFileExists() { } @Test - void testIsActiveExistsLeavesFileUnchanged() { + void isActiveExistsLeavesFileUnchanged() { Profile profile = newExistsProfile("file.txt"); - assertEquals("file.txt", profile.getActivation().getFile().getExists()); + assertThat(profile.getActivation().getFile().getExists()).isEqualTo("file.txt"); assertActivation(true, profile, context); - assertEquals("file.txt", profile.getActivation().getFile().getExists()); + assertThat(profile.getActivation().getFile().getExists()).isEqualTo("file.txt"); } private Profile newExistsProfile(String filePath) { diff --git a/impl/maven-impl/src/test/java/org/apache/maven/impl/model/profile/JdkVersionProfileActivatorTest.java b/impl/maven-impl/src/test/java/org/apache/maven/impl/model/profile/JdkVersionProfileActivatorTest.java index 9f72bee87af1..e3ed739dad10 100644 --- a/impl/maven-impl/src/test/java/org/apache/maven/impl/model/profile/JdkVersionProfileActivatorTest.java +++ b/impl/maven-impl/src/test/java/org/apache/maven/impl/model/profile/JdkVersionProfileActivatorTest.java @@ -26,9 +26,7 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests {@link JdkVersionProfileActivator}. @@ -55,7 +53,7 @@ private Map newProperties(String javaVersion) { } @Test - void testNullSafe() throws Exception { + void nullSafe() throws Exception { Profile p = Profile.newInstance(); assertActivation(false, p, newContext(null, null)); @@ -66,7 +64,7 @@ void testNullSafe() throws Exception { } @Test - void testPrefix() throws Exception { + void prefix() throws Exception { Profile profile = newProfile("1.4"); assertActivation(true, profile, newContext(null, newProperties("1.4"))); @@ -80,7 +78,7 @@ void testPrefix() throws Exception { } @Test - void testPrefixNegated() throws Exception { + void prefixNegated() throws Exception { Profile profile = newProfile("!1.4"); assertActivation(false, profile, newContext(null, newProperties("1.4"))); @@ -94,7 +92,7 @@ void testPrefixNegated() throws Exception { } @Test - void testVersionRangeInclusiveBounds() throws Exception { + void versionRangeInclusiveBounds() throws Exception { Profile profile = newProfile("[1.5,1.6]"); assertActivation(false, profile, newContext(null, newProperties("1.4"))); @@ -115,7 +113,7 @@ void testVersionRangeInclusiveBounds() throws Exception { } @Test - void testVersionRangeExclusiveBounds() throws Exception { + void versionRangeExclusiveBounds() throws Exception { Profile profile = newProfile("(1.3,1.6)"); assertActivation(false, profile, newContext(null, newProperties("1.3"))); @@ -137,7 +135,7 @@ void testVersionRangeExclusiveBounds() throws Exception { } @Test - void testVersionRangeInclusiveLowerBound() throws Exception { + void versionRangeInclusiveLowerBound() throws Exception { Profile profile = newProfile("[1.5,)"); assertActivation(false, profile, newContext(null, newProperties("1.4"))); @@ -158,7 +156,7 @@ void testVersionRangeInclusiveLowerBound() throws Exception { } @Test - void testVersionRangeExclusiveUpperBound() throws Exception { + void versionRangeExclusiveUpperBound() throws Exception { Profile profile = newProfile("(,1.6)"); assertActivation(true, profile, newContext(null, newProperties("1.5"))); @@ -174,7 +172,7 @@ void testVersionRangeExclusiveUpperBound() throws Exception { } @Test - void testRubbishJavaVersion() { + void rubbishJavaVersion() { Profile profile = newProfile("[1.8,)"); assertActivationWithProblems(profile, newContext(null, newProperties("Pūteketeke")), "invalid JDK version"); @@ -187,10 +185,10 @@ private void assertActivationWithProblems( Profile profile, ProfileActivationContext context, String warningContains) { SimpleProblemCollector problems = new SimpleProblemCollector(); - assertFalse(activator.isActive(profile, context, problems)); + assertThat(activator.isActive(profile, context, problems)).isFalse(); - assertEquals(0, problems.getErrors().size()); - assertEquals(1, problems.getWarnings().size()); - assertTrue(problems.getWarnings().get(0).contains(warningContains)); + assertThat(problems.getErrors().size()).isEqualTo(0); + assertThat(problems.getWarnings().size()).isEqualTo(1); + assertThat(problems.getWarnings().get(0).contains(warningContains)).isTrue(); } } diff --git a/impl/maven-impl/src/test/java/org/apache/maven/impl/model/profile/OperatingSystemProfileActivatorTest.java b/impl/maven-impl/src/test/java/org/apache/maven/impl/model/profile/OperatingSystemProfileActivatorTest.java index 4f228a5f1495..d247207a4439 100644 --- a/impl/maven-impl/src/test/java/org/apache/maven/impl/model/profile/OperatingSystemProfileActivatorTest.java +++ b/impl/maven-impl/src/test/java/org/apache/maven/impl/model/profile/OperatingSystemProfileActivatorTest.java @@ -51,7 +51,7 @@ private Map newProperties(String osName, String osVersion, Strin } @Test - void testVersionStringComparison() throws Exception { + void versionStringComparison() throws Exception { Profile profile = newProfile(ActivationOS.newBuilder().version("6.5.0-1014-aws")); assertActivation(true, profile, newContext(null, newProperties("linux", "6.5.0-1014-aws", "amd64"))); @@ -61,7 +61,7 @@ void testVersionStringComparison() throws Exception { } @Test - void testVersionRegexMatching() throws Exception { + void versionRegexMatching() throws Exception { Profile profile = newProfile(ActivationOS.newBuilder().version("regex:.*aws")); assertActivation(true, profile, newContext(null, newProperties("linux", "6.5.0-1014-aws", "amd64"))); @@ -71,7 +71,7 @@ void testVersionRegexMatching() throws Exception { } @Test - void testName() { + void name() { Profile profile = newProfile(ActivationOS.newBuilder().name("windows")); assertActivation(false, profile, newContext(null, newProperties("linux", "6.5.0-1014-aws", "amd64"))); @@ -79,7 +79,7 @@ void testName() { } @Test - void testNegatedName() { + void negatedName() { Profile profile = newProfile(ActivationOS.newBuilder().name("!windows")); assertActivation(true, profile, newContext(null, newProperties("linux", "6.5.0-1014-aws", "amd64"))); @@ -87,7 +87,7 @@ void testNegatedName() { } @Test - void testArch() { + void arch() { Profile profile = newProfile(ActivationOS.newBuilder().arch("amd64")); assertActivation(true, profile, newContext(null, newProperties("linux", "6.5.0-1014-aws", "amd64"))); @@ -95,7 +95,7 @@ void testArch() { } @Test - void testNegatedArch() { + void negatedArch() { Profile profile = newProfile(ActivationOS.newBuilder().arch("!amd64")); assertActivation(false, profile, newContext(null, newProperties("linux", "6.5.0-1014-aws", "amd64"))); @@ -103,7 +103,7 @@ void testNegatedArch() { } @Test - void testFamily() { + void family() { Profile profile = newProfile(ActivationOS.newBuilder().family("windows")); assertActivation(false, profile, newContext(null, newProperties("linux", "6.5.0-1014-aws", "amd64"))); @@ -111,7 +111,7 @@ void testFamily() { } @Test - void testNegatedFamily() { + void negatedFamily() { Profile profile = newProfile(ActivationOS.newBuilder().family("!windows")); assertActivation(true, profile, newContext(null, newProperties("linux", "6.5.0-1014-aws", "amd64"))); @@ -119,7 +119,7 @@ void testNegatedFamily() { } @Test - void testAllOsConditions() { + void allOsConditions() { Profile profile = newProfile(ActivationOS.newBuilder() .family("windows") .name("windows") @@ -133,7 +133,7 @@ void testAllOsConditions() { } @Test - void testCapitalOsName() { + void capitalOsName() { Profile profile = newProfile(ActivationOS.newBuilder() .family("Mac") .name("Mac OS X") diff --git a/impl/maven-impl/src/test/java/org/apache/maven/impl/model/profile/PropertyProfileActivatorTest.java b/impl/maven-impl/src/test/java/org/apache/maven/impl/model/profile/PropertyProfileActivatorTest.java index 0f193614b20f..d9fb5898e9b7 100644 --- a/impl/maven-impl/src/test/java/org/apache/maven/impl/model/profile/PropertyProfileActivatorTest.java +++ b/impl/maven-impl/src/test/java/org/apache/maven/impl/model/profile/PropertyProfileActivatorTest.java @@ -54,7 +54,7 @@ private Map newProperties(String key, String value) { } @Test - void testNullSafe() throws Exception { + void nullSafe() throws Exception { Profile p = Profile.newInstance(); assertActivation(false, p, newContext(null, null)); @@ -65,7 +65,7 @@ void testNullSafe() throws Exception { } @Test - void testWithNameOnlyUserProperty() throws Exception { + void withNameOnlyUserProperty() throws Exception { Profile profile = newProfile("prop", null); assertActivation(true, profile, newContext(newProperties("prop", "value"), null)); @@ -76,7 +76,7 @@ void testWithNameOnlyUserProperty() throws Exception { } @Test - void testWithNameOnlySystemProperty() throws Exception { + void withNameOnlySystemProperty() throws Exception { Profile profile = newProfile("prop", null); assertActivation(true, profile, newContext(null, newProperties("prop", "value"))); @@ -87,7 +87,7 @@ void testWithNameOnlySystemProperty() throws Exception { } @Test - void testWithNegatedNameOnlyUserProperty() throws Exception { + void withNegatedNameOnlyUserProperty() throws Exception { Profile profile = newProfile("!prop", null); assertActivation(false, profile, newContext(newProperties("prop", "value"), null)); @@ -98,7 +98,7 @@ void testWithNegatedNameOnlyUserProperty() throws Exception { } @Test - void testWithNegatedNameOnlySystemProperty() throws Exception { + void withNegatedNameOnlySystemProperty() throws Exception { Profile profile = newProfile("!prop", null); assertActivation(false, profile, newContext(null, newProperties("prop", "value"))); @@ -109,7 +109,7 @@ void testWithNegatedNameOnlySystemProperty() throws Exception { } @Test - void testWithValueUserProperty() throws Exception { + void withValueUserProperty() throws Exception { Profile profile = newProfile("prop", "value"); assertActivation(true, profile, newContext(newProperties("prop", "value"), null)); @@ -120,7 +120,7 @@ void testWithValueUserProperty() throws Exception { } @Test - void testWithValueSystemProperty() throws Exception { + void withValueSystemProperty() throws Exception { Profile profile = newProfile("prop", "value"); assertActivation(true, profile, newContext(null, newProperties("prop", "value"))); @@ -131,7 +131,7 @@ void testWithValueSystemProperty() throws Exception { } @Test - void testWithNegatedValueUserProperty() throws Exception { + void withNegatedValueUserProperty() throws Exception { Profile profile = newProfile("prop", "!value"); assertActivation(false, profile, newContext(newProperties("prop", "value"), null)); @@ -142,7 +142,7 @@ void testWithNegatedValueUserProperty() throws Exception { } @Test - void testWithNegatedValueSystemProperty() throws Exception { + void withNegatedValueSystemProperty() throws Exception { Profile profile = newProfile("prop", "!value"); assertActivation(false, profile, newContext(null, newProperties("prop", "value"))); @@ -153,7 +153,7 @@ void testWithNegatedValueSystemProperty() throws Exception { } @Test - void testWithValueUserPropertyDominantOverSystemProperty() throws Exception { + void withValueUserPropertyDominantOverSystemProperty() throws Exception { Profile profile = newProfile("prop", "value"); Map props1 = newProperties("prop", "value"); diff --git a/impl/maven-impl/src/test/java/org/apache/maven/impl/model/reflection/ReflectionValueExtractorTest.java b/impl/maven-impl/src/test/java/org/apache/maven/impl/model/reflection/ReflectionValueExtractorTest.java index a47d213e35e0..2afbc0eab171 100644 --- a/impl/maven-impl/src/test/java/org/apache/maven/impl/model/reflection/ReflectionValueExtractorTest.java +++ b/impl/maven-impl/src/test/java/org/apache/maven/impl/model/reflection/ReflectionValueExtractorTest.java @@ -42,14 +42,12 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertNull; +import static org.assertj.core.api.Assertions.assertThat; /** * ReflectionValueExtractorTest class. */ -public class ReflectionValueExtractorTest { +class ReflectionValueExtractorTest { private Project project; /** @@ -86,26 +84,26 @@ void setUp() { * @throws Exception if any. */ @Test - void testValueExtraction() throws Exception { + void valueExtraction() throws Exception { // ---------------------------------------------------------------------- // Top level values // ---------------------------------------------------------------------- - assertEquals("4.0.0", ReflectionValueExtractor.evaluate("project.modelVersion", project)); + assertThat(ReflectionValueExtractor.evaluate("project.modelVersion", project)).isEqualTo("4.0.0"); - assertEquals("org.apache.maven", ReflectionValueExtractor.evaluate("project.groupId", project)); + assertThat(ReflectionValueExtractor.evaluate("project.groupId", project)).isEqualTo("org.apache.maven"); - assertEquals("maven-core", ReflectionValueExtractor.evaluate("project.artifactId", project)); + assertThat(ReflectionValueExtractor.evaluate("project.artifactId", project)).isEqualTo("maven-core"); - assertEquals("Maven", ReflectionValueExtractor.evaluate("project.name", project)); + assertThat(ReflectionValueExtractor.evaluate("project.name", project)).isEqualTo("Maven"); - assertEquals("2.0-SNAPSHOT", ReflectionValueExtractor.evaluate("project.version", project)); + assertThat(ReflectionValueExtractor.evaluate("project.version", project)).isEqualTo("2.0-SNAPSHOT"); // ---------------------------------------------------------------------- // SCM // ---------------------------------------------------------------------- - assertEquals("scm-connection", ReflectionValueExtractor.evaluate("project.scm.connection", project)); + assertThat(ReflectionValueExtractor.evaluate("project.scm.connection", project)).isEqualTo("scm-connection"); // ---------------------------------------------------------------------- // Dependencies @@ -113,9 +111,9 @@ void testValueExtraction() throws Exception { List dependencies = (List) ReflectionValueExtractor.evaluate("project.dependencies", project); - assertNotNull(dependencies); + assertThat(dependencies).isNotNull(); - assertEquals(2, dependencies.size()); + assertThat(dependencies.size()).isEqualTo(2); // ---------------------------------------------------------------------- // Dependencies - using index notation @@ -124,37 +122,37 @@ void testValueExtraction() throws Exception { // List Dependency dependency = (Dependency) ReflectionValueExtractor.evaluate("project.dependencies[0]", project); - assertNotNull(dependency); + assertThat(dependency).isNotNull(); - assertEquals("dep1", dependency.getArtifactId()); + assertThat(dependency.getArtifactId()).isEqualTo("dep1"); String artifactId = (String) ReflectionValueExtractor.evaluate("project.dependencies[1].artifactId", project); - assertEquals("dep2", artifactId); + assertThat(artifactId).isEqualTo("dep2"); // Array dependency = (Dependency) ReflectionValueExtractor.evaluate("project.dependenciesAsArray[0]", project); - assertNotNull(dependency); + assertThat(dependency).isNotNull(); - assertEquals("dep1", dependency.getArtifactId()); + assertThat(dependency.getArtifactId()).isEqualTo("dep1"); artifactId = (String) ReflectionValueExtractor.evaluate("project.dependenciesAsArray[1].artifactId", project); - assertEquals("dep2", artifactId); + assertThat(artifactId).isEqualTo("dep2"); // Map dependency = (Dependency) ReflectionValueExtractor.evaluate("project.dependenciesAsMap(dep1)", project); - assertNotNull(dependency); + assertThat(dependency).isNotNull(); - assertEquals("dep1", dependency.getArtifactId()); + assertThat(dependency.getArtifactId()).isEqualTo("dep1"); artifactId = (String) ReflectionValueExtractor.evaluate("project.dependenciesAsMap(dep2).artifactId", project); - assertEquals("dep2", artifactId); + assertThat(artifactId).isEqualTo("dep2"); // ---------------------------------------------------------------------- // Build @@ -162,7 +160,7 @@ void testValueExtraction() throws Exception { Build build = (Build) ReflectionValueExtractor.evaluate("project.build", project); - assertNotNull(build); + assertThat(build).isNotNull(); } /** @@ -171,10 +169,10 @@ void testValueExtraction() throws Exception { * @throws Exception if any. */ @Test - public void testValueExtractorWithAInvalidExpression() throws Exception { - assertNull(ReflectionValueExtractor.evaluate("project.foo", project)); - assertNull(ReflectionValueExtractor.evaluate("project.dependencies[10]", project)); - assertNull(ReflectionValueExtractor.evaluate("project.dependencies[0].foo", project)); + void valueExtractorWithAInvalidExpression() throws Exception { + assertThat(ReflectionValueExtractor.evaluate("project.foo", project)).isNull(); + assertThat(ReflectionValueExtractor.evaluate("project.dependencies[10]", project)).isNull(); + assertThat(ReflectionValueExtractor.evaluate("project.dependencies[0].foo", project)).isNull(); } /** @@ -183,11 +181,11 @@ public void testValueExtractorWithAInvalidExpression() throws Exception { * @throws Exception if any. */ @Test - public void testMappedDottedKey() throws Exception { + void mappedDottedKey() throws Exception { Map map = new HashMap(); map.put("a.b", "a.b-value"); - assertEquals("a.b-value", ReflectionValueExtractor.evaluate("h.value(a.b)", new ValueHolder(map))); + assertThat(ReflectionValueExtractor.evaluate("h.value(a.b)", new ValueHolder(map))).isEqualTo("a.b-value"); } /** @@ -196,13 +194,13 @@ public void testMappedDottedKey() throws Exception { * @throws Exception if any. */ @Test - public void testIndexedMapped() throws Exception { + void indexedMapped() throws Exception { Map map = new HashMap(); map.put("a", "a-value"); List list = new ArrayList(); list.add(map); - assertEquals("a-value", ReflectionValueExtractor.evaluate("h.value[0](a)", new ValueHolder(list))); + assertThat(ReflectionValueExtractor.evaluate("h.value[0](a)", new ValueHolder(list))).isEqualTo("a-value"); } /** @@ -211,12 +209,12 @@ public void testIndexedMapped() throws Exception { * @throws Exception if any. */ @Test - public void testMappedIndexed() throws Exception { + void mappedIndexed() throws Exception { List list = new ArrayList(); list.add("a-value"); Map map = new HashMap(); map.put("a", list); - assertEquals("a-value", ReflectionValueExtractor.evaluate("h.value(a)[0]", new ValueHolder(map))); + assertThat(ReflectionValueExtractor.evaluate("h.value(a)[0]", new ValueHolder(map))).isEqualTo("a-value"); } /** @@ -225,10 +223,10 @@ public void testMappedIndexed() throws Exception { * @throws Exception if any. */ @Test - public void testMappedMissingDot() throws Exception { + void mappedMissingDot() throws Exception { Map map = new HashMap(); map.put("a", new ValueHolder("a-value")); - assertNull(ReflectionValueExtractor.evaluate("h.value(a)value", new ValueHolder(map))); + assertThat(ReflectionValueExtractor.evaluate("h.value(a)value", new ValueHolder(map))).isNull(); } /** @@ -237,10 +235,10 @@ public void testMappedMissingDot() throws Exception { * @throws Exception if any. */ @Test - public void testIndexedMissingDot() throws Exception { + void indexedMissingDot() throws Exception { List list = new ArrayList(); list.add(new ValueHolder("a-value")); - assertNull(ReflectionValueExtractor.evaluate("h.value[0]value", new ValueHolder(list))); + assertThat(ReflectionValueExtractor.evaluate("h.value[0]value", new ValueHolder(list))).isNull(); } /** @@ -249,8 +247,8 @@ public void testIndexedMissingDot() throws Exception { * @throws Exception if any. */ @Test - public void testDotDot() throws Exception { - assertNull(ReflectionValueExtractor.evaluate("h..value", new ValueHolder("value"))); + void dotDot() throws Exception { + assertThat(ReflectionValueExtractor.evaluate("h..value", new ValueHolder("value"))).isNull(); } /** @@ -259,17 +257,17 @@ public void testDotDot() throws Exception { * @throws Exception if any. */ @Test - public void testBadIndexedSyntax() throws Exception { + void badIndexedSyntax() throws Exception { List list = new ArrayList(); list.add("a-value"); Object value = new ValueHolder(list); - assertNull(ReflectionValueExtractor.evaluate("h.value[", value)); - assertNull(ReflectionValueExtractor.evaluate("h.value[]", value)); - assertNull(ReflectionValueExtractor.evaluate("h.value[a]", value)); - assertNull(ReflectionValueExtractor.evaluate("h.value[0", value)); - assertNull(ReflectionValueExtractor.evaluate("h.value[0)", value)); - assertNull(ReflectionValueExtractor.evaluate("h.value[-1]", value)); + assertThat(ReflectionValueExtractor.evaluate("h.value[", value)).isNull(); + assertThat(ReflectionValueExtractor.evaluate("h.value[]", value)).isNull(); + assertThat(ReflectionValueExtractor.evaluate("h.value[a]", value)).isNull(); + assertThat(ReflectionValueExtractor.evaluate("h.value[0", value)).isNull(); + assertThat(ReflectionValueExtractor.evaluate("h.value[0)", value)).isNull(); + assertThat(ReflectionValueExtractor.evaluate("h.value[-1]", value)).isNull(); } /** @@ -278,15 +276,15 @@ public void testBadIndexedSyntax() throws Exception { * @throws Exception if any. */ @Test - public void testBadMappedSyntax() throws Exception { + void badMappedSyntax() throws Exception { Map map = new HashMap(); map.put("a", "a-value"); Object value = new ValueHolder(map); - assertNull(ReflectionValueExtractor.evaluate("h.value(", value)); - assertNull(ReflectionValueExtractor.evaluate("h.value()", value)); - assertNull(ReflectionValueExtractor.evaluate("h.value(a", value)); - assertNull(ReflectionValueExtractor.evaluate("h.value(a]", value)); + assertThat(ReflectionValueExtractor.evaluate("h.value(", value)).isNull(); + assertThat(ReflectionValueExtractor.evaluate("h.value()", value)).isNull(); + assertThat(ReflectionValueExtractor.evaluate("h.value(a", value)).isNull(); + assertThat(ReflectionValueExtractor.evaluate("h.value(a]", value)).isNull(); } /** @@ -295,7 +293,7 @@ public void testBadMappedSyntax() throws Exception { * @throws Exception if any. */ @Test - public void testIllegalIndexedType() throws Exception { + void illegalIndexedType() throws Exception { try { ReflectionValueExtractor.evaluate("h.value[1]", new ValueHolder("string")); } catch (Exception e) { @@ -309,7 +307,7 @@ public void testIllegalIndexedType() throws Exception { * @throws Exception if any. */ @Test - public void testIllegalMappedType() throws Exception { + void illegalMappedType() throws Exception { try { ReflectionValueExtractor.evaluate("h.value(key)", new ValueHolder("string")); } catch (Exception e) { @@ -323,8 +321,8 @@ public void testIllegalMappedType() throws Exception { * @throws Exception if any. */ @Test - public void testTrimRootToken() throws Exception { - assertNull(ReflectionValueExtractor.evaluate("project", project, true)); + void trimRootToken() throws Exception { + assertThat(ReflectionValueExtractor.evaluate("project", project, true)).isNull(); } /** @@ -333,18 +331,12 @@ public void testTrimRootToken() throws Exception { * @throws Exception if any. */ @Test - public void testArtifactMap() throws Exception { - assertEquals( - "g0", - ((Artifact) ReflectionValueExtractor.evaluate("project.artifactMap(g0:a0:c0)", project)).getGroupId()); - assertEquals( - "a1", - ((Artifact) ReflectionValueExtractor.evaluate("project.artifactMap(g1:a1:c1)", project)) - .getArtifactId()); - assertEquals( - "c2", - ((Artifact) ReflectionValueExtractor.evaluate("project.artifactMap(g2:a2:c2)", project)) - .getClassifier()); + void artifactMap() throws Exception { + assertThat(((Artifact) ReflectionValueExtractor.evaluate("project.artifactMap(g0:a0:c0)", project)).getGroupId()).isEqualTo("g0"); + assertThat(((Artifact) ReflectionValueExtractor.evaluate("project.artifactMap(g1:a1:c1)", project)) + .getArtifactId()).isEqualTo("a1"); + assertThat(((Artifact) ReflectionValueExtractor.evaluate("project.artifactMap(g2:a2:c2)", project)) + .getClassifier()).isEqualTo("c2"); } public static class Artifact { @@ -547,16 +539,7 @@ public String getConnection() { } } - public static class ValueHolder { - private final Object value; - - public ValueHolder(Object value) { - this.value = value; - } - - public Object getValue() { - return value; - } + public record ValueHolder(Object value) { } /** @@ -565,10 +548,10 @@ public Object getValue() { * @throws Exception if any. */ @Test - public void testRootPropertyRegression() throws Exception { + void rootPropertyRegression() throws Exception { Project project = new Project(); project.setDescription("c:\\\\org\\apache\\test"); Object evalued = ReflectionValueExtractor.evaluate("description", project); - assertNotNull(evalued); + assertThat(evalued).isNotNull(); } } diff --git a/impl/maven-impl/src/test/java/org/apache/maven/impl/resolver/DefaultModelResolverTest.java b/impl/maven-impl/src/test/java/org/apache/maven/impl/resolver/DefaultModelResolverTest.java index e680267895ad..ce82647552b1 100644 --- a/impl/maven-impl/src/test/java/org/apache/maven/impl/resolver/DefaultModelResolverTest.java +++ b/impl/maven-impl/src/test/java/org/apache/maven/impl/resolver/DefaultModelResolverTest.java @@ -39,11 +39,10 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertThrows; /** * Test cases for the project {@code ModelResolver} implementation. @@ -58,9 +57,8 @@ void setup() { Path localRepoPath = basedir.resolve("target/local-repo"); Path remoteRepoPath = basedir.resolve("src/test/remote-repo"); Session s = ApiRunner.createSession( - injector -> { - injector.bindInstance(DefaultModelResolverTest.class, this); - }, + injector -> + injector.bindInstance(DefaultModelResolverTest.class, this), localRepoPath); RemoteRepository remoteRepository = s.createRemoteRepository( RemoteRepository.CENTRAL_ID, remoteRepoPath.toUri().toString()); @@ -68,65 +66,56 @@ void setup() { } @Test - void testResolveParentThrowsModelResolverExceptionWhenNotFound() throws Exception { + void resolveParentThrowsModelResolverExceptionWhenNotFound() throws Exception { final Parent parent = Parent.newBuilder() .groupId("org.apache") .artifactId("apache") .version("0") .build(); - ModelResolverException e = assertThrows( - ModelResolverException.class, - () -> newModelResolver().resolveModel(session, null, parent, new AtomicReference<>()), - "Expected 'ModelResolverException' not thrown."); - assertNotNull(e.getMessage()); + ModelResolverException e = assertThatExceptionOfType(ModelResolverException.class).as("Expected 'ModelResolverException' not thrown.").isThrownBy(() -> newModelResolver().resolveModel(session, null, parent, new AtomicReference<>())).actual(); + assertThat(e.getMessage()).isNotNull(); assertThat(e.getMessage(), containsString("Could not find artifact org.apache:apache:pom:0 in central")); } @Test - void testResolveParentThrowsModelResolverExceptionWhenNoMatchingVersionFound() throws Exception { + void resolveParentThrowsModelResolverExceptionWhenNoMatchingVersionFound() throws Exception { final Parent parent = Parent.newBuilder() .groupId("org.apache") .artifactId("apache") .version("[2.0,2.1)") .build(); - ModelResolverException e = assertThrows( - ModelResolverException.class, - () -> newModelResolver().resolveModel(session, null, parent, new AtomicReference<>()), - "Expected 'ModelResolverException' not thrown."); - assertEquals("No versions matched the requested parent version range '[2.0,2.1)'", e.getMessage()); + ModelResolverException e = assertThatExceptionOfType(ModelResolverException.class).as("Expected 'ModelResolverException' not thrown.").isThrownBy(() -> newModelResolver().resolveModel(session, null, parent, new AtomicReference<>())).actual(); + assertThat(e.getMessage()).isEqualTo("No versions matched the requested parent version range '[2.0,2.1)'"); } @Test - void testResolveParentThrowsModelResolverExceptionWhenUsingRangesWithoutUpperBound() throws Exception { + void resolveParentThrowsModelResolverExceptionWhenUsingRangesWithoutUpperBound() throws Exception { final Parent parent = Parent.newBuilder() .groupId("org.apache") .artifactId("apache") .version("[1,)") .build(); - ModelResolverException e = assertThrows( - ModelResolverException.class, - () -> newModelResolver().resolveModel(session, null, parent, new AtomicReference<>()), - "Expected 'ModelResolverException' not thrown."); - assertEquals("The requested parent version range '[1,)' does not specify an upper bound", e.getMessage()); + ModelResolverException e = assertThatExceptionOfType(ModelResolverException.class).as("Expected 'ModelResolverException' not thrown.").isThrownBy(() -> newModelResolver().resolveModel(session, null, parent, new AtomicReference<>())).actual(); + assertThat(e.getMessage()).isEqualTo("The requested parent version range '[1,)' does not specify an upper bound"); } @Test - void testResolveParentSuccessfullyResolvesExistingParentWithoutRange() throws Exception { + void resolveParentSuccessfullyResolvesExistingParentWithoutRange() throws Exception { final Parent parent = Parent.newBuilder() .groupId("org.apache") .artifactId("apache") .version("1") .build(); - assertNotNull(this.newModelResolver().resolveModel(session, null, parent, new AtomicReference<>())); - assertEquals("1", parent.getVersion()); + assertThat(this.newModelResolver().resolveModel(session, null, parent, new AtomicReference<>())).isNotNull(); + assertThat(parent.getVersion()).isEqualTo("1"); } @Test - void testResolveParentSuccessfullyResolvesExistingParentUsingHighestVersion() throws Exception { + void resolveParentSuccessfullyResolvesExistingParentUsingHighestVersion() throws Exception { final Parent parent = Parent.newBuilder() .groupId("org.apache") .artifactId("apache") @@ -134,70 +123,61 @@ void testResolveParentSuccessfullyResolvesExistingParentUsingHighestVersion() th .build(); AtomicReference modified = new AtomicReference<>(); - assertNotNull(this.newModelResolver().resolveModel(session, null, parent, modified)); - assertEquals("1", modified.get().getVersion()); + assertThat(this.newModelResolver().resolveModel(session, null, parent, modified)).isNotNull(); + assertThat(modified.get().getVersion()).isEqualTo("1"); } @Test - void testResolveDependencyThrowsModelResolverExceptionWhenNotFound() throws Exception { + void resolveDependencyThrowsModelResolverExceptionWhenNotFound() throws Exception { final Dependency dependency = Dependency.newBuilder() .groupId("org.apache") .artifactId("apache") .version("0") .build(); - ModelResolverException e = assertThrows( - ModelResolverException.class, - () -> newModelResolver().resolveModel(session, null, dependency, new AtomicReference<>()), - "Expected 'ModelResolverException' not thrown."); - assertNotNull(e.getMessage()); + ModelResolverException e = assertThatExceptionOfType(ModelResolverException.class).as("Expected 'ModelResolverException' not thrown.").isThrownBy(() -> newModelResolver().resolveModel(session, null, dependency, new AtomicReference<>())).actual(); + assertThat(e.getMessage()).isNotNull(); assertThat(e.getMessage(), containsString("Could not find artifact org.apache:apache:pom:0 in central")); } @Test - void testResolveDependencyThrowsModelResolverExceptionWhenNoMatchingVersionFound() throws Exception { + void resolveDependencyThrowsModelResolverExceptionWhenNoMatchingVersionFound() throws Exception { final Dependency dependency = Dependency.newBuilder() .groupId("org.apache") .artifactId("apache") .version("[2.0,2.1)") .build(); - ModelResolverException e = assertThrows( - ModelResolverException.class, - () -> newModelResolver().resolveModel(session, null, dependency, new AtomicReference<>()), - "Expected 'ModelResolverException' not thrown."); - assertEquals("No versions matched the requested dependency version range '[2.0,2.1)'", e.getMessage()); + ModelResolverException e = assertThatExceptionOfType(ModelResolverException.class).as("Expected 'ModelResolverException' not thrown.").isThrownBy(() -> newModelResolver().resolveModel(session, null, dependency, new AtomicReference<>())).actual(); + assertThat(e.getMessage()).isEqualTo("No versions matched the requested dependency version range '[2.0,2.1)'"); } @Test - void testResolveDependencyThrowsModelResolverExceptionWhenUsingRangesWithoutUpperBound() throws Exception { + void resolveDependencyThrowsModelResolverExceptionWhenUsingRangesWithoutUpperBound() throws Exception { final Dependency dependency = Dependency.newBuilder() .groupId("org.apache") .artifactId("apache") .version("[1,)") .build(); - ModelResolverException e = assertThrows( - ModelResolverException.class, - () -> newModelResolver().resolveModel(session, null, dependency, new AtomicReference<>()), - "Expected 'ModelResolverException' not thrown."); - assertEquals("The requested dependency version range '[1,)' does not specify an upper bound", e.getMessage()); + ModelResolverException e = assertThatExceptionOfType(ModelResolverException.class).as("Expected 'ModelResolverException' not thrown.").isThrownBy(() -> newModelResolver().resolveModel(session, null, dependency, new AtomicReference<>())).actual(); + assertThat(e.getMessage()).isEqualTo("The requested dependency version range '[1,)' does not specify an upper bound"); } @Test - void testResolveDependencySuccessfullyResolvesExistingDependencyWithoutRange() throws Exception { + void resolveDependencySuccessfullyResolvesExistingDependencyWithoutRange() throws Exception { final Dependency dependency = Dependency.newBuilder() .groupId("org.apache") .artifactId("apache") .version("1") .build(); - assertNotNull(this.newModelResolver().resolveModel(session, null, dependency, new AtomicReference<>())); - assertEquals("1", dependency.getVersion()); + assertThat(this.newModelResolver().resolveModel(session, null, dependency, new AtomicReference<>())).isNotNull(); + assertThat(dependency.getVersion()).isEqualTo("1"); } @Test - void testResolveDependencySuccessfullyResolvesExistingDependencyUsingHighestVersion() throws Exception { + void resolveDependencySuccessfullyResolvesExistingDependencyUsingHighestVersion() throws Exception { final Dependency dependency = Dependency.newBuilder() .groupId("org.apache") .artifactId("apache") @@ -205,8 +185,8 @@ void testResolveDependencySuccessfullyResolvesExistingDependencyUsingHighestVers .build(); AtomicReference modified = new AtomicReference<>(); - assertNotNull(this.newModelResolver().resolveModel(session, null, dependency, modified)); - assertEquals("1", modified.get().getVersion()); + assertThat(this.newModelResolver().resolveModel(session, null, dependency, modified)).isNotNull(); + assertThat(modified.get().getVersion()).isEqualTo("1"); } private ModelResolver newModelResolver() throws Exception { diff --git a/impl/maven-impl/src/test/java/org/apache/maven/impl/standalone/DiTest.java b/impl/maven-impl/src/test/java/org/apache/maven/impl/standalone/DiTest.java index 10512a384373..fd02267b7b13 100644 --- a/impl/maven-impl/src/test/java/org/apache/maven/impl/standalone/DiTest.java +++ b/impl/maven-impl/src/test/java/org/apache/maven/impl/standalone/DiTest.java @@ -26,14 +26,14 @@ import org.apache.maven.impl.ExtensibleEnumRegistries; import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; class DiTest { @Test - void testGenerics() { + void generics() { Set types = Types.getAllSuperTypes(ExtensibleEnumRegistries.DefaultPathScopeRegistry.class); - assertNotNull(types); + assertThat(types).isNotNull(); Injector injector = Injector.create(); injector.bindImplicit(ExtensibleEnumRegistries.DefaultPathScopeRegistry.class); diff --git a/impl/maven-impl/src/test/java/org/apache/maven/impl/standalone/RequestTraceTest.java b/impl/maven-impl/src/test/java/org/apache/maven/impl/standalone/RequestTraceTest.java index 934350477018..d5e75ee059d5 100644 --- a/impl/maven-impl/src/test/java/org/apache/maven/impl/standalone/RequestTraceTest.java +++ b/impl/maven-impl/src/test/java/org/apache/maven/impl/standalone/RequestTraceTest.java @@ -48,14 +48,12 @@ import org.eclipse.aether.transport.file.FileTransporterFactory; import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; class RequestTraceTest { @Test - void testTraces() { + void traces() { Session session = ApiRunner.createSession(injector -> { injector.bindInstance(RequestTraceTest.class, this); }); @@ -68,7 +66,7 @@ void testTraces() { .requestType(ModelBuilderRequest.RequestType.BUILD_PROJECT) .recursive(true) .build()); - assertNotNull(result.getEffectiveModel()); + assertThat(result.getEffectiveModel()).isNotNull(); List events = new CopyOnWriteArrayList<>(); ((DefaultRepositorySystemSession) InternalSession.from(session).getSession()) @@ -82,9 +80,9 @@ public void artifactResolved(RepositoryEvent event) { ArtifactCoordinates coords = session.createArtifactCoordinates("org.apache.maven:maven-api-core:4.0.0-alpha-13"); DownloadedArtifact res = session.resolveArtifact(coords); - assertNotNull(res); - assertNotNull(res.getPath()); - assertTrue(Files.exists(res.getPath())); + assertThat(res).isNotNull(); + assertThat(res.getPath()).isNotNull(); + assertThat(Files.exists(res.getPath())).isTrue(); Node node = session.getService(DependencyResolver.class) .collect(DependencyResolverRequest.builder() @@ -101,15 +99,15 @@ public void artifactResolved(RepositoryEvent event) { for (RepositoryEvent event : events) { org.eclipse.aether.RequestTrace trace = event.getTrace(); - assertNotNull(trace); + assertThat(trace).isNotNull(); RequestTrace rTrace = RequestTraceHelper.toMaven("collect", trace); - assertNotNull(rTrace); - assertNotNull(rTrace.parent()); + assertThat(rTrace).isNotNull(); + assertThat(rTrace.parent()).isNotNull(); } - assertNotNull(node); - assertEquals(6, node.getChildren().size()); + assertThat(node).isNotNull(); + assertThat(node.getChildren().size()).isEqualTo(6); } @Provides diff --git a/impl/maven-impl/src/test/java/org/apache/maven/impl/standalone/TestApiStandalone.java b/impl/maven-impl/src/test/java/org/apache/maven/impl/standalone/TestApiStandalone.java index a0c519a9eaf5..e00d504072bb 100644 --- a/impl/maven-impl/src/test/java/org/apache/maven/impl/standalone/TestApiStandalone.java +++ b/impl/maven-impl/src/test/java/org/apache/maven/impl/standalone/TestApiStandalone.java @@ -38,14 +38,12 @@ import org.eclipse.aether.transport.file.FileTransporterFactory; import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; class TestApiStandalone { @Test - void testStandalone() { + void standalone() { Session session = ApiRunner.createSession(injector -> { injector.bindInstance(TestApiStandalone.class, this); }); @@ -58,18 +56,18 @@ void testStandalone() { .requestType(ModelBuilderRequest.RequestType.BUILD_PROJECT) .recursive(true) .build()); - assertNotNull(result.getEffectiveModel()); + assertThat(result.getEffectiveModel()).isNotNull(); ArtifactCoordinates coords = session.createArtifactCoordinates("org.apache.maven:maven-api-core:4.0.0-alpha-13"); DownloadedArtifact res = session.resolveArtifact(coords); - assertNotNull(res); - assertNotNull(res.getPath()); - assertTrue(Files.exists(res.getPath())); + assertThat(res).isNotNull(); + assertThat(res.getPath()).isNotNull(); + assertThat(Files.exists(res.getPath())).isTrue(); Node node = session.collectDependencies(session.createDependencyCoordinates(coords), PathScope.MAIN_RUNTIME); - assertNotNull(node); - assertEquals(6, node.getChildren().size()); + assertThat(node).isNotNull(); + assertThat(node.getChildren().size()).isEqualTo(6); } @Provides diff --git a/impl/maven-impl/src/test/java/org/apache/maven/impl/util/PhasingExecutorTest.java b/impl/maven-impl/src/test/java/org/apache/maven/impl/util/PhasingExecutorTest.java index 8d234d28a087..581723ba24c6 100644 --- a/impl/maven-impl/src/test/java/org/apache/maven/impl/util/PhasingExecutorTest.java +++ b/impl/maven-impl/src/test/java/org/apache/maven/impl/util/PhasingExecutorTest.java @@ -26,7 +26,7 @@ class PhasingExecutorTest { @Test - void testPhaser() { + void phaser() { try (PhasingExecutor p = new PhasingExecutor(Executors.newFixedThreadPool(4))) { p.execute(() -> waitSomeTime(p, 2)); }