From 58b19ac9e0981ac44898a33ecb8724d211341e90 Mon Sep 17 00:00:00 2001 From: Heiko Klare Date: Fri, 5 Jan 2024 16:32:03 +0100 Subject: [PATCH] Replace Hamcrest assertions with AssertJ assertions Comprehensive assertions can be defined with different libraries, of which Hamcrest and AssertJ are two of the most popular ones. While Platform tests currently only use Hamcrest at some places, AssertJ has several advantages including: * Easier to apply and learn due to fluent API rather than matcher providing comprehensive code completion support * Higher expressiveness by easily chaining multiple assertions on the same object * Better comprehensibility by chaining instead of nesting calls and starting `assertThat` always with the subject under test and not a custom message in case such a message is desired This change migrates the existing usages of Hamcrest to AssertJ (except for one custom Matcher implementation). Doing that it also makes use of String formatting rather than String concatenation with a potential slight performance improvement. --- .../console/InputStreamMonitorTests.java | 50 +++-- .../console/OutputStreamMonitorTests.java | 61 ++++--- .../console/ProcessConsoleManagerTests.java | 5 +- .../tests/console/ProcessConsoleTests.java | 8 +- ...LaunchConfigurationTabGroupViewerTest.java | 25 +-- .../META-INF/MANIFEST.MF | 3 +- .../core/tests/filesystem/FileCacheTest.java | 6 +- .../filesystem/OpenOutputStreamTest.java | 5 +- .../internal/builders/BuildContextTest.java | 94 +++++----- .../internal/builders/BuilderNatureTest.java | 8 +- .../internal/builders/ContextBuilder.java | 8 +- .../builders/CustomBuildTriggerTest.java | 9 +- .../builders/ParallelBuildChainTest.java | 48 +++-- .../builders/RelaxedSchedRuleBuilderTest.java | 8 +- .../BuildProjectFromMultipleJobsTest.java | 14 +- .../tests/internal/localstore/CopyTest.java | 16 +- .../SafeChunkyInputOutputStreamTest.java | 25 ++- .../ModelObjectReaderWriterTest.java | 171 +++++++++--------- .../resources/ProjectBuildConfigsTest.java | 58 +++--- .../ProjectDynamicReferencesTest.java | 151 +++++++--------- .../resources/ProjectPreferencesTest.java | 6 +- .../resources/ProjectReferencesTest.java | 102 +++++------ .../resources/WorkspacePreferencesTest.java | 5 +- .../IResourceChangeListenerTest.java | 11 +- .../core/tests/resources/IResourceTest.java | 6 +- .../tests/resources/ISynchronizerTest.java | 47 ++--- .../core/tests/resources/MarkerTest.java | 163 +++++++++-------- .../resources/MarkersChangeListener.java | 33 ++-- .../core/tests/resources/NatureTest.java | 78 ++++---- .../tests/resources/ResourceTestUtil.java | 13 +- .../resources/TeamPrivateMemberTest.java | 66 ++++--- .../refresh/RefreshProviderTest.java | 10 +- .../tests/resources/session/Bug_266907.java | 12 +- .../ProjectDescriptionDynamicTest.java | 26 ++- .../session/WorkspaceDescriptionTest.java | 20 +- .../tests/resources/usecase/IFileTest.java | 95 +++++----- .../tests/resources/usecase/IFolderTest.java | 160 ++++++++-------- .../tests/resources/usecase/IProjectTest.java | 107 +++++------ .../META-INF/MANIFEST.MF | 2 + .../tests/harness/FussyProgressMonitor.java | 56 +++--- .../ConfigurationSessionTestSuite.java | 2 + .../META-INF/MANIFEST.MF | 1 + .../preferences/EclipsePreferencesTest.java | 23 +-- .../runtime/XmlProcessorFactoryTest.java | 9 +- .../tests/runtime/jobs/BeginEndRuleTest.java | 18 +- .../tests/runtime/jobs/IJobManagerTest.java | 9 +- .../core/tests/runtime/jobs/JobTest.java | 30 +-- .../tests/runtime/jobs/OrderedLockTest.java | 10 +- .../META-INF/MANIFEST.MF | 1 + .../tests/core/RepositoryProviderTests.java | 15 +- .../ui/SaveableCompareEditorInputTest.java | 5 +- 51 files changed, 892 insertions(+), 1022 deletions(-) diff --git a/debug/org.eclipse.debug.tests/src/org/eclipse/debug/tests/console/InputStreamMonitorTests.java b/debug/org.eclipse.debug.tests/src/org/eclipse/debug/tests/console/InputStreamMonitorTests.java index 72e84b10056..9a02104bc9c 100644 --- a/debug/org.eclipse.debug.tests/src/org/eclipse/debug/tests/console/InputStreamMonitorTests.java +++ b/debug/org.eclipse.debug.tests/src/org/eclipse/debug/tests/console/InputStreamMonitorTests.java @@ -13,7 +13,7 @@ *******************************************************************************/ package org.eclipse.debug.tests.console; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import java.io.IOException; import java.io.OutputStream; @@ -29,9 +29,6 @@ import org.eclipse.debug.tests.TestsPlugin; import org.junit.Test; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.is; - /** * Tests the {@link InputStreamMonitor}. */ @@ -49,21 +46,21 @@ public void testInputStreamMonitor() throws Exception { OutputStream outputFromSysin = new PipedOutputStream(sysin); ) { monitor = new InputStreamMonitor(outputFromSysin); - byte[] content = new byte[100]; - for (int i = 0; i < content.length; i++) { - content[i] = (byte) (i % 255); + byte[] originalContent = new byte[100]; + for (int i = 0; i < originalContent.length; i++) { + originalContent[i] = (byte) (i % 255); } - int half = content.length / 2; - monitor.write(content, 0, half); + int half = originalContent.length / 2; + monitor.write(originalContent, 0, half); monitor.startMonitoring(); - monitor.write(content, half, content.length - half); - waitForElementsInStream(sysin, content.length); - - byte[] readBack = new byte[content.length]; - int read = sysin.read(readBack); - assertEquals("Monitor wrote to few bytes.", read, content.length); - assertThat("Monitor wrote to much bytes.", sysin.available(), is(0)); - assertThat("Monitor wrote wrong content.", readBack, is(content)); + monitor.write(originalContent, half, originalContent.length - half); + waitForElementsInStream(sysin, originalContent.length); + + byte[] contentWrittenByMonitor = new byte[originalContent.length]; + sysin.read(contentWrittenByMonitor); + int additionalBytesWritten = sysin.available(); + assertThat(additionalBytesWritten).isZero(); + assertThat(contentWrittenByMonitor).isEqualTo(originalContent); } finally { if (monitor != null) { monitor.close(); @@ -80,7 +77,7 @@ private void waitForElementsInStream(PipedInputStream sysin, int numberOfElement } return true; }, CONDITION_TIMEOUT_IN_MILLIS); - assertThat(sysin.available(), is(numberOfElements)); + assertThat(sysin.available()).isEqualTo(numberOfElements); } /** @@ -98,7 +95,8 @@ public void testNullCharset() throws Exception { byte[] readBack = new byte[1000]; int len = sysin.read(readBack); - assertThat("Monitor wrote wrong content.", text, is(new String(readBack, 0, len))); + String readContent = new String(readBack, 0, len); + assertThat(readContent).isEqualTo(text); } finally { if (monitor != null) { monitor.close(); @@ -126,34 +124,34 @@ public void testClose() throws Exception { { ClosableTestOutputStream testStream = new ClosableTestOutputStream(); InputStreamMonitor monitor = new InputStreamMonitor(testStream); - assertThat("Stream closed to early.", testStream.numClosed, is(0)); + assertThat(testStream.numClosed).withFailMessage("stream closed too early").isZero(); monitor.closeInputStream(); TestUtil.waitWhile(() -> testStream.numClosed == 0, CONDITION_TIMEOUT_IN_MILLIS); - assertThat("Stream not closed.", testStream.numClosed, is(1)); + assertThat(testStream.numClosed).withFailMessage("stream not closed").isNotZero(); } { ClosableTestOutputStream testStream = new ClosableTestOutputStream(); InputStreamMonitor monitor = new InputStreamMonitor(testStream); monitor.startMonitoring(threadName); - assertThat("Stream closed to early.", testStream.numClosed, is(0)); + assertThat(testStream.numClosed).withFailMessage("stream closed too early").isZero(); monitor.close(); TestUtil.waitWhile(() -> testStream.numClosed == 0, CONDITION_TIMEOUT_IN_MILLIS); - assertThat("Stream not closed.", testStream.numClosed, is(1)); + assertThat(testStream.numClosed).withFailMessage("stream not closed").isNotZero(); } { ClosableTestOutputStream testStream = new ClosableTestOutputStream(); InputStreamMonitor monitor = new InputStreamMonitor(testStream); monitor.startMonitoring(threadName); - assertThat("Stream closed to early.", testStream.numClosed, is(0)); + assertThat(testStream.numClosed).withFailMessage("stream closed too early").isZero(); monitor.closeInputStream(); monitor.close(); monitor.close(); TestUtil.waitWhile(() -> testStream.numClosed == 0, CONDITION_TIMEOUT_IN_MILLIS); - assertThat("Stream not closed or to often.", testStream.numClosed, is(1)); + assertThat(testStream.numClosed).as("stream should be closed once").isEqualTo(1); } TestUtil.waitWhile(() -> getInputStreamMonitorThreads.get() > 0, CONDITION_TIMEOUT_IN_MILLIS); - assertThat("Leaked monitor threads.", getInputStreamMonitorThreads.get(), is(0L)); + assertThat(getInputStreamMonitorThreads.get()).as("leaked monitor threads").isZero(); } /** diff --git a/debug/org.eclipse.debug.tests/src/org/eclipse/debug/tests/console/OutputStreamMonitorTests.java b/debug/org.eclipse.debug.tests/src/org/eclipse/debug/tests/console/OutputStreamMonitorTests.java index f1b41c9ac1b..b96d24e9b27 100644 --- a/debug/org.eclipse.debug.tests/src/org/eclipse/debug/tests/console/OutputStreamMonitorTests.java +++ b/debug/org.eclipse.debug.tests/src/org/eclipse/debug/tests/console/OutputStreamMonitorTests.java @@ -13,6 +13,8 @@ *******************************************************************************/ package org.eclipse.debug.tests.console; +import static org.assertj.core.api.Assertions.assertThat; + import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; @@ -36,9 +38,6 @@ import org.junit.After; import org.junit.Before; import org.junit.Test; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.empty; /** * Tests the {@link OutputStreamMonitor}. @@ -78,7 +77,7 @@ public byte[] getRecordedBytes() { } public void assertNoExceptions() { - assertThat(exceptions, is(empty())); + assertThat(exceptions).isEmpty(); } } @@ -134,32 +133,36 @@ public void testBufferedOutputStreamMonitor() throws Exception { monitor.startMonitoring(); binaryListener.waitForBytes(2); streamListener.waitForBytes(1); - String contents = monitor.getContents(); - assertThat("Monitor read wrong content.", contents, is(input.substring(0, 1))); - assertThat("Notified and buffered content differ.", streamListener.getRecordedChars(), is(contents)); - assertThat("Failed to access buffered content twice.", monitor.getContents(), is(contents)); - byte[] data = monitor.getData(); - byte[] expected = new byte[2]; - System.arraycopy(byteInput, 0, expected, 0, 2); - assertThat("Monitor read wrong binary content.", data, is(expected)); - assertThat("Notified and buffered binary content differ.", binaryListener.getRecordedBytes(), is(data)); - assertThat("Failed to access buffered binary content twice.", monitor.getData(), is(data)); + String monitorContents = monitor.getContents(); + assertThat(monitorContents).isEqualTo(input.substring(0, 1)); + assertThat(streamListener.getRecordedChars()).isEqualTo(monitorContents); + String monitorContentsOnSecondAccess = monitor.getContents(); + assertThat(monitorContentsOnSecondAccess).isEqualTo(monitorContents); + byte[] binaryMonitorData = monitor.getData(); + byte[] expectedBinaryData = new byte[2]; + System.arraycopy(byteInput, 0, expectedBinaryData, 0, 2); + assertThat(binaryMonitorData).isEqualTo(expectedBinaryData); + assertThat(binaryListener.getRecordedBytes()).isEqualTo(binaryMonitorData); + byte[] binaryMonitorDataOnSecondAccess = monitor.getData(); + assertThat(binaryMonitorDataOnSecondAccess).isEqualTo(binaryMonitorData); monitor.flushContents(); sysout.write(byteInput, 2, byteInput.length - 2); sysout.flush(); binaryListener.waitForBytes(byteInput.length); streamListener.waitForBytes(new String(byteInput).length()); - contents = monitor.getContents(); - assertThat("Monitor buffered wrong content.", contents, is(input.substring(1))); - assertThat("Failed to access buffered content twice.", monitor.getContents(), is(contents)); - assertThat("Wrong content through listener.", streamListener.getRecordedChars(), is(input)); - data = monitor.getData(); - expected = new byte[byteInput.length - 2]; - System.arraycopy(byteInput, 2, expected, 0, expected.length); - assertThat("Monitor read wrong binary content.", data, is(expected)); - assertThat("Failed to access buffered binary content twice.", monitor.getData(), is(data)); - assertThat("Wrong binary content through listener.", binaryListener.getRecordedBytes(), is(byteInput)); + monitorContents = monitor.getContents(); + assertThat(monitorContents).isEqualTo(input.substring(1)); + monitorContentsOnSecondAccess = monitor.getContents(); + assertThat(monitorContentsOnSecondAccess).isEqualTo(monitorContents); + assertThat(streamListener.getRecordedChars()).isEqualTo(input); + binaryMonitorData = monitor.getData(); + expectedBinaryData = new byte[byteInput.length - 2]; + System.arraycopy(byteInput, 2, expectedBinaryData, 0, expectedBinaryData.length); + assertThat(binaryMonitorData).isEqualTo(expectedBinaryData); + binaryMonitorDataOnSecondAccess = monitor.getData(); + assertThat(binaryMonitorDataOnSecondAccess).isEqualTo(binaryMonitorData); + assertThat(binaryListener.getRecordedBytes()).isEqualTo(byteInput); binaryListener.assertNoExceptions(); } @@ -183,20 +186,20 @@ public void testUnbufferedOutputStreamMonitor() throws Exception { monitor.startMonitoring(); binaryListener.waitForBytes(2); streamListener.waitForBytes(1); - assertThat("Monitor read wrong content.", streamListener.getRecordedChars(), is(input.substring(0, 1))); + assertThat(streamListener.getRecordedChars()).isEqualTo(input.substring(0, 1)); byte[] expected = new byte[2]; System.arraycopy(byteInput, 0, expected, 0, 2); - assertThat("Monitor read wrong binary content.", binaryListener.getRecordedBytes(), is(expected)); + assertThat(binaryListener.getRecordedBytes()).isEqualTo(expected); monitor.flushContents(); sysout.write(byteInput, 2, byteInput.length - 2); sysout.flush(); binaryListener.waitForBytes(byteInput.length); streamListener.waitForBytes(new String(byteInput).length()); - assertThat("Wrong content through listener.", streamListener.getRecordedChars(), is(input)); + assertThat(streamListener.getRecordedChars()).isEqualTo(input); expected = new byte[byteInput.length - 2]; System.arraycopy(byteInput, 2, expected, 0, expected.length); - assertThat("Wrong binary content through listener.", binaryListener.getRecordedBytes(), is(byteInput)); + assertThat(binaryListener.getRecordedBytes()).isEqualTo(byteInput); binaryListener.assertNoExceptions(); } @@ -223,7 +226,7 @@ public void testNullCharset() throws Exception { sysout.flush(); streamListener.waitForBytes(input.length()); - assertThat("Monitor read wrong content.", streamListener.getRecordedChars(), is(input)); + assertThat(streamListener.getRecordedChars()).isEqualTo(input); } /** diff --git a/debug/org.eclipse.debug.tests/src/org/eclipse/debug/tests/console/ProcessConsoleManagerTests.java b/debug/org.eclipse.debug.tests/src/org/eclipse/debug/tests/console/ProcessConsoleManagerTests.java index ed43b4bb166..d1f00215fe1 100644 --- a/debug/org.eclipse.debug.tests/src/org/eclipse/debug/tests/console/ProcessConsoleManagerTests.java +++ b/debug/org.eclipse.debug.tests/src/org/eclipse/debug/tests/console/ProcessConsoleManagerTests.java @@ -14,8 +14,7 @@ package org.eclipse.debug.tests.console; import static java.util.stream.Collectors.joining; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.hasSize; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; @@ -130,7 +129,7 @@ public void testBug546710_ConsoleCreationRaceCondition() throws Exception { String launchesString = Stream.of(launches).map(launch -> Stream.of(launch.getProcesses()).map(IProcess::getLabel).collect(joining(",", "[", "]"))).collect(joining()); String consolesString = openConsoles.stream().map(IConsole::getName).collect(joining()); String failureMessage = String.format("ProcessConsoleManager and LaunchManager got out of sync.\nLaunches: %s\nConsoles: %s", launchesString, consolesString); - assertThat(failureMessage, openConsoles, hasSize(launches.length)); + assertThat(openConsoles).as(failureMessage).hasSameSizeAs(launches); final ConsoleRemoveAllTerminatedAction removeAction = new ConsoleRemoveAllTerminatedAction(); assertTrue("Remove terminated action should be enabled.", removeAction.isEnabled() || launchManager.getLaunches().length == 0); diff --git a/debug/org.eclipse.debug.tests/src/org/eclipse/debug/tests/console/ProcessConsoleTests.java b/debug/org.eclipse.debug.tests/src/org/eclipse/debug/tests/console/ProcessConsoleTests.java index 499a4ebb2c2..703df0ed581 100644 --- a/debug/org.eclipse.debug.tests/src/org/eclipse/debug/tests/console/ProcessConsoleTests.java +++ b/debug/org.eclipse.debug.tests/src/org/eclipse/debug/tests/console/ProcessConsoleTests.java @@ -13,9 +13,7 @@ *******************************************************************************/ package org.eclipse.debug.tests.console; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.empty; -import static org.hamcrest.Matchers.is; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; @@ -110,7 +108,7 @@ public void tearDown() throws Exception { super.tearDown(); - assertThat("Test triggered errors.", loggedErrors, empty()); + assertThat(loggedErrors).as("logged errors").isEmpty(); } /** @@ -527,7 +525,7 @@ public void testBinaryOutputToFile() throws Exception { } byte[] receivedOutput = Files.readAllBytes(outFile.toPath()); - assertThat("unexpected output", receivedOutput, is(output)); + assertThat(receivedOutput).as("received output").isEqualTo(output); } /** diff --git a/debug/org.eclipse.debug.tests/src/org/eclipse/debug/tests/ui/LaunchConfigurationTabGroupViewerTest.java b/debug/org.eclipse.debug.tests/src/org/eclipse/debug/tests/ui/LaunchConfigurationTabGroupViewerTest.java index fc6ed459dfd..6e4176b2540 100644 --- a/debug/org.eclipse.debug.tests/src/org/eclipse/debug/tests/ui/LaunchConfigurationTabGroupViewerTest.java +++ b/debug/org.eclipse.debug.tests/src/org/eclipse/debug/tests/ui/LaunchConfigurationTabGroupViewerTest.java @@ -11,9 +11,8 @@ package org.eclipse.debug.tests.ui; +import static java.util.function.Predicate.not; import static org.assertj.core.api.Assertions.assertThat; -import static org.hamcrest.CoreMatchers.not; -import static org.hamcrest.MatcherAssert.assertThat; import java.util.Arrays; import java.util.concurrent.atomic.AtomicReference; @@ -32,6 +31,7 @@ import org.eclipse.debug.ui.ILaunchConfigurationTabGroup; import org.eclipse.swt.widgets.Display; import org.junit.Before; +import org.junit.Ignore; import org.junit.Test; public class LaunchConfigurationTabGroupViewerTest { @@ -56,9 +56,9 @@ public void createDialog() throws CoreException { ILaunchConfigurationTab[] tabs = tabGroup.getTabs(); assertThat(tabs).hasSizeGreaterThanOrEqualTo(2); - assertThat(tabs).allMatch(SpyTab.class::isInstance, "Use only SpyTabs in the group"); - long typesOfTabs = Arrays.stream(tabs).map(Object::getClass).distinct().count(); - assertThat("There are tabs of the exact same type in the group", tabs.length == typesOfTabs); + assertThat(tabs).allSatisfy(tab -> assertThat(tab).isInstanceOf(SpyTab.class)); + int typesOfTabs = Math.toIntExact(Arrays.stream(tabs).map(Object::getClass).distinct().count()); + assertThat(tabs).withFailMessage("there are tabs of the exact same type in the group").hasSize(typesOfTabs); } @Test @@ -71,7 +71,7 @@ public void testAllTabsAreInitializedByDefault() { final ILaunchConfigurationTab[] tabs = runOnDialog(createAndSelect1LaunchConfig); for (int i = 0; i < tabs.length; i++) { - assertThat("Tab " + i + " was not initialized", ((SpyTab) tabs[i]).isInitialized()); + assertThat(((SpyTab) tabs[i])).withFailMessage("tab %s was not initialized", i).matches(SpyTab::isInitialized); } } @@ -83,7 +83,7 @@ public void testFirstTabIsActivatedByDefault() { }; final ILaunchConfigurationTab[] tabs = runOnDialog(createAndSelect1LaunchConfig); - assertThat("The 1st tab was not activated", ((SpyTab) tabs[0]).isActivated()); + assertThat(((SpyTab) tabs[0])).matches(SpyTab::isActivated, "is activated"); } @Test @@ -104,11 +104,12 @@ public void testOtherTabInOtherConfigIsActivated() { final ILaunchConfigurationTab[] tabs = runOnDialog(setActiveTab); - assertThat("The 1st tab of the other launch configuration shouldn't have been activated", not(((SpyTab) tabs[0]).isActivated())); - assertThat("The tab was not activated", ((SpyTab) tabs[secondTabIndex]).isActivated()); + assertThat((SpyTab) tabs[0]).withFailMessage("the 1st tab of the other launch configuration shouldn't have been activated").matches(not(SpyTab::isActivated)); + assertThat((SpyTab) tabs[secondTabIndex]).matches(SpyTab::isActivated, "is activated"); } @Test + @Ignore("https://github.com/eclipse-platform/eclipse.platform/issues/1075") public void testOnlyDefaultTabInOtherConfigIsActivated() { int overflowTabIndex = Integer.MAX_VALUE; @@ -126,11 +127,11 @@ public void testOnlyDefaultTabInOtherConfigIsActivated() { final ILaunchConfigurationTab[] tabs = runOnDialog(setActiveTab); - assertThat("The 1st tab of the other launch configuration should have been activated", ((SpyTab) tabs[0]).isActivated()); + assertThat(((SpyTab) tabs[0])).withFailMessage("the 1st tab of the other launch configuration should have been activated").matches(SpyTab::isActivated); // All other tabs should not have been initialized for (int i = 1; i < tabs.length; i++) { - assertThat("Tab " + i + " should not have been initialized", not(((SpyTab) tabs[i]).isInitialized())); + assertThat((SpyTab) tabs[i]).withFailMessage("tab %s should not have been initialized", i).matches(not(SpyTab::isInitialized)); } } @@ -148,7 +149,7 @@ public void testOtherTabIsActivated() { final ILaunchConfigurationTab[] tabs = runOnDialog(setActiveTab); - assertThat("The tab was not activated", ((SpyTab) tabs[secondTabIndex]).isActivated()); + assertThat((SpyTab) tabs[secondTabIndex]).matches(SpyTab::isActivated, "is activated"); } private ILaunchConfigurationWorkingCopy createLaunchConfigurationInstance() throws CoreException { diff --git a/resources/tests/org.eclipse.core.tests.resources/META-INF/MANIFEST.MF b/resources/tests/org.eclipse.core.tests.resources/META-INF/MANIFEST.MF index 673909110fb..bd4d1805234 100644 --- a/resources/tests/org.eclipse.core.tests.resources/META-INF/MANIFEST.MF +++ b/resources/tests/org.eclipse.core.tests.resources/META-INF/MANIFEST.MF @@ -34,7 +34,8 @@ Require-Bundle: org.eclipse.core.resources, org.eclipse.core.filesystem, org.eclipse.core.runtime, org.eclipse.pde.junit.runtime;bundle-version="3.5.0" -Import-Package: org.mockito +Import-Package: org.mockito, + org.assertj.core.api Bundle-ActivationPolicy: lazy Bundle-RequiredExecutionEnvironment: JavaSE-17 Eclipse-BundleShape: dir diff --git a/resources/tests/org.eclipse.core.tests.resources/src/org/eclipse/core/tests/filesystem/FileCacheTest.java b/resources/tests/org.eclipse.core.tests.resources/src/org/eclipse/core/tests/filesystem/FileCacheTest.java index bbd41b72dca..6234603d6cd 100755 --- a/resources/tests/org.eclipse.core.tests.resources/src/org/eclipse/core/tests/filesystem/FileCacheTest.java +++ b/resources/tests/org.eclipse.core.tests.resources/src/org/eclipse/core/tests/filesystem/FileCacheTest.java @@ -13,10 +13,8 @@ *******************************************************************************/ package org.eclipse.core.tests.filesystem; +import static org.assertj.core.api.Assertions.assertThat; import static org.eclipse.core.tests.filesystem.FileSystemTestUtil.getMonitor; -import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.CoreMatchers.not; -import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; @@ -78,7 +76,7 @@ public void testCacheFile() throws Exception { } // old cache will be out of date - assertThat("2.0", newContents, not(equalTo(getBytes(cachedFile)))); + assertThat(newContents).isNotEqualTo(getBytes(cachedFile)); // fetching the cache again should return up to date file cachedFile = store.toLocalFile(EFS.CACHE, getMonitor()); diff --git a/resources/tests/org.eclipse.core.tests.resources/src/org/eclipse/core/tests/filesystem/OpenOutputStreamTest.java b/resources/tests/org.eclipse.core.tests.resources/src/org/eclipse/core/tests/filesystem/OpenOutputStreamTest.java index dc1a99803e5..be4b24ef863 100644 --- a/resources/tests/org.eclipse.core.tests.resources/src/org/eclipse/core/tests/filesystem/OpenOutputStreamTest.java +++ b/resources/tests/org.eclipse.core.tests.resources/src/org/eclipse/core/tests/filesystem/OpenOutputStreamTest.java @@ -13,10 +13,9 @@ *******************************************************************************/ package org.eclipse.core.tests.filesystem; +import static org.assertj.core.api.Assertions.assertThat; import static org.eclipse.core.tests.filesystem.FileSystemTestUtil.ensureDoesNotExist; import static org.eclipse.core.tests.filesystem.FileSystemTestUtil.getMonitor; -import static org.hamcrest.CoreMatchers.hasItem; -import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThrows; import static org.junit.Assert.assertTrue; @@ -85,7 +84,7 @@ private static void assertExists(IFileStore store) throws CoreException { // check that the parent knows about it IFileInfo[] children = store.getParent().childInfos(EFS.NONE, getMonitor()); List childrenNames = Stream.of(children).map(IFileInfo::getName).collect(Collectors.toList()); - assertThat(childrenNames, hasItem(store.getName())); + assertThat(childrenNames).contains(store.getName()); } @Test diff --git a/resources/tests/org.eclipse.core.tests.resources/src/org/eclipse/core/tests/internal/builders/BuildContextTest.java b/resources/tests/org.eclipse.core.tests.resources/src/org/eclipse/core/tests/internal/builders/BuildContextTest.java index a4e29949f02..6c469694020 100644 --- a/resources/tests/org.eclipse.core.tests.resources/src/org/eclipse/core/tests/internal/builders/BuildContextTest.java +++ b/resources/tests/org.eclipse.core.tests.resources/src/org/eclipse/core/tests/internal/builders/BuildContextTest.java @@ -13,15 +13,13 @@ *******************************************************************************/ package org.eclipse.core.tests.internal.builders; +import static org.assertj.core.api.Assertions.assertThat; import static org.eclipse.core.resources.ResourcesPlugin.getWorkspace; import static org.eclipse.core.tests.resources.ResourceTestUtil.createInWorkspace; import static org.eclipse.core.tests.resources.ResourceTestUtil.createTestMonitor; import static org.eclipse.core.tests.resources.ResourceTestUtil.setAutoBuilding; import static org.eclipse.core.tests.resources.ResourceTestUtil.updateProjectDescription; import static org.eclipse.core.tests.resources.ResourceTestUtil.waitForBuild; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.arrayContaining; -import static org.hamcrest.Matchers.emptyArray; import org.eclipse.core.internal.events.BuildContext; import org.eclipse.core.internal.resources.BuildConfiguration; @@ -136,22 +134,22 @@ public void testBuildContext() { IBuildContext context; context = new BuildContext(p0v0, new IBuildConfiguration[] {p0v0, p1v0}, buildOrder); - assertThat(context.getAllReferencedBuildConfigs(), emptyArray()); - assertThat(context.getAllReferencingBuildConfigs(), arrayContaining(p0v1, p1v0)); - assertThat(context.getRequestedConfigs(), arrayContaining(p0v0, p1v0)); + assertThat(context.getAllReferencedBuildConfigs()).isEmpty(); + assertThat(context.getAllReferencingBuildConfigs()).containsExactly(p0v1, p1v0); + assertThat(context.getRequestedConfigs()).containsExactly(p0v0, p1v0); context = new BuildContext(p0v1, buildOrder, buildOrder); - assertThat(context.getAllReferencedBuildConfigs(), arrayContaining(p0v0)); - assertThat(context.getAllReferencingBuildConfigs(), arrayContaining(p1v0)); + assertThat(context.getAllReferencedBuildConfigs()).containsExactly(p0v0); + assertThat(context.getAllReferencingBuildConfigs()).containsExactly(p1v0); context = new BuildContext(p1v0, buildOrder, buildOrder); - assertThat(context.getAllReferencedBuildConfigs(), arrayContaining(p0v0, p0v1)); - assertThat(context.getAllReferencingBuildConfigs(), emptyArray()); + assertThat(context.getAllReferencedBuildConfigs()).containsExactly(p0v0, p0v1); + assertThat(context.getAllReferencingBuildConfigs()).isEmpty(); // And it works with no build context too context = new BuildContext(p1v0); - assertThat(context.getAllReferencedBuildConfigs(), emptyArray()); - assertThat(context.getAllReferencingBuildConfigs(), emptyArray()); + assertThat(context.getAllReferencedBuildConfigs()).isEmpty(); + assertThat(context.getAllReferencingBuildConfigs()).isEmpty(); } @Test @@ -164,8 +162,8 @@ public void testSingleProjectBuild() throws CoreException { ContextBuilder.assertValid(); IBuildContext context = ContextBuilder.getContext(project0.getActiveBuildConfig()); - assertThat(context.getAllReferencedBuildConfigs(), emptyArray()); - assertThat(context.getAllReferencingBuildConfigs(), emptyArray()); + assertThat(context.getAllReferencedBuildConfigs()).isEmpty(); + assertThat(context.getAllReferencingBuildConfigs()).isEmpty(); // Change the active build configuration will cause the project to be rebuilt ContextBuilder.clearStats(); @@ -174,7 +172,7 @@ public void testSingleProjectBuild() throws CoreException { ContextBuilder.assertValid(); context = ContextBuilder.getContext(newActive); - assertThat(context.getAllReferencedBuildConfigs(), emptyArray()); + assertThat(context.getAllReferencedBuildConfigs()).isEmpty(); } /** @@ -190,18 +188,18 @@ public void testWorkspaceBuildProject() throws CoreException { ContextBuilder.assertValid(); IBuildContext context = ContextBuilder.getContext(project0.getActiveBuildConfig()); - assertThat(context.getAllReferencedBuildConfigs(), - arrayContaining(project2.getActiveBuildConfig(), project1.getActiveBuildConfig())); - assertThat(context.getAllReferencingBuildConfigs(), emptyArray()); + assertThat(context.getAllReferencedBuildConfigs()).containsExactly(project2.getActiveBuildConfig(), + project1.getActiveBuildConfig()); + assertThat(context.getAllReferencingBuildConfigs()).isEmpty(); context = ContextBuilder.getBuilder(project1.getActiveBuildConfig()).contextForLastBuild; - assertThat(context.getAllReferencedBuildConfigs(), arrayContaining(project2.getActiveBuildConfig())); - assertThat(context.getAllReferencingBuildConfigs(), arrayContaining(project0.getActiveBuildConfig())); + assertThat(context.getAllReferencedBuildConfigs()).containsExactly(project2.getActiveBuildConfig()); + assertThat(context.getAllReferencingBuildConfigs()).containsExactly(project0.getActiveBuildConfig()); context = ContextBuilder.getBuilder(project2.getActiveBuildConfig()).contextForLastBuild; - assertThat(context.getAllReferencedBuildConfigs(), emptyArray()); - assertThat(context.getAllReferencingBuildConfigs(), - arrayContaining(project1.getActiveBuildConfig(), project0.getActiveBuildConfig())); + assertThat(context.getAllReferencedBuildConfigs()).isEmpty(); + assertThat(context.getAllReferencingBuildConfigs()).containsExactly(project1.getActiveBuildConfig(), + project0.getActiveBuildConfig()); // Build just project0 ContextBuilder.clearStats(); @@ -209,8 +207,8 @@ public void testWorkspaceBuildProject() throws CoreException { ContextBuilder.assertValid(); context = ContextBuilder.getContext(project0.getActiveBuildConfig()); - assertThat(context.getAllReferencedBuildConfigs(), emptyArray()); - assertThat(context.getAllReferencingBuildConfigs(), emptyArray()); + assertThat(context.getAllReferencedBuildConfigs()).isEmpty(); + assertThat(context.getAllReferencingBuildConfigs()).isEmpty(); } /** @@ -225,18 +223,16 @@ public void testWorkspaceBuildProjects() throws CoreException { ContextBuilder.assertValid(); IBuildContext context = ContextBuilder.getContext(project0.getActiveBuildConfig()); - assertThat(context.getAllReferencedBuildConfigs(), - arrayContaining(project2.getActiveBuildConfig(), project1.getActiveBuildConfig())); - assertThat(context.getAllReferencingBuildConfigs(), emptyArray()); + assertThat(context.getAllReferencedBuildConfigs()).containsExactly(project2.getActiveBuildConfig(), project1.getActiveBuildConfig()); + assertThat(context.getAllReferencingBuildConfigs()).isEmpty(); context = ContextBuilder.getBuilder(project1.getActiveBuildConfig()).contextForLastBuild; - assertThat(context.getAllReferencedBuildConfigs(), arrayContaining(project2.getActiveBuildConfig())); - assertThat(context.getAllReferencingBuildConfigs(), arrayContaining(project0.getActiveBuildConfig())); + assertThat(context.getAllReferencedBuildConfigs()).containsExactly(project2.getActiveBuildConfig()); + assertThat(context.getAllReferencingBuildConfigs()).containsExactly(project0.getActiveBuildConfig()); context = ContextBuilder.getBuilder(project2.getActiveBuildConfig()).contextForLastBuild; - assertThat(context.getAllReferencedBuildConfigs(), emptyArray()); - assertThat(context.getAllReferencingBuildConfigs(), - arrayContaining(project1.getActiveBuildConfig(), project0.getActiveBuildConfig())); + assertThat(context.getAllReferencedBuildConfigs()).isEmpty(); + assertThat(context.getAllReferencingBuildConfigs()).containsExactly(project1.getActiveBuildConfig(), project0.getActiveBuildConfig()); } /** @@ -253,18 +249,18 @@ public void testReferenceActiveVariant() throws CoreException { ContextBuilder.assertValid(); IBuildContext context = ContextBuilder.getContext(project0.getActiveBuildConfig()); - assertThat(context.getAllReferencedBuildConfigs(), - arrayContaining(project2.getActiveBuildConfig(), project1.getActiveBuildConfig())); - assertThat(context.getAllReferencingBuildConfigs(), emptyArray()); + assertThat(context.getAllReferencedBuildConfigs()).containsExactly(project2.getActiveBuildConfig(), + project1.getActiveBuildConfig()); + assertThat(context.getAllReferencingBuildConfigs()).isEmpty(); context = ContextBuilder.getBuilder(project1.getActiveBuildConfig()).contextForLastBuild; - assertThat(context.getAllReferencedBuildConfigs(), arrayContaining(project2.getActiveBuildConfig())); - assertThat(context.getAllReferencingBuildConfigs(), arrayContaining(project0.getActiveBuildConfig())); + assertThat(context.getAllReferencedBuildConfigs()).containsExactly(project2.getActiveBuildConfig()); + assertThat(context.getAllReferencingBuildConfigs()).containsExactly(project0.getActiveBuildConfig()); context = ContextBuilder.getBuilder(project2.getActiveBuildConfig()).contextForLastBuild; - assertThat(context.getAllReferencedBuildConfigs(), emptyArray()); - assertThat(context.getAllReferencingBuildConfigs(), - arrayContaining(project1.getActiveBuildConfig(), project0.getActiveBuildConfig())); + assertThat(context.getAllReferencedBuildConfigs()).isEmpty(); + assertThat(context.getAllReferencingBuildConfigs()).containsExactly(project1.getActiveBuildConfig(), + project0.getActiveBuildConfig()); } /** @@ -283,13 +279,13 @@ public void testReferenceVariantTwice() throws CoreException { ContextBuilder.assertValid(); IBuildContext context = ContextBuilder.getContext(project0.getActiveBuildConfig()); - assertThat(context.getAllReferencedBuildConfigs(), arrayContaining(project1.getActiveBuildConfig())); - assertThat(context.getAllReferencingBuildConfigs(), emptyArray()); - assertThat(context.getRequestedConfigs(), arrayContaining(project0.getActiveBuildConfig())); + assertThat(context.getAllReferencedBuildConfigs()).containsExactly(project1.getActiveBuildConfig()); + assertThat(context.getAllReferencingBuildConfigs()).isEmpty(); + assertThat(context.getRequestedConfigs()).containsExactly(project0.getActiveBuildConfig()); context = ContextBuilder.getBuilder(project1.getActiveBuildConfig()).contextForLastBuild; - assertThat(context.getAllReferencedBuildConfigs(), emptyArray()); - assertThat(context.getAllReferencingBuildConfigs(), arrayContaining(project0.getActiveBuildConfig())); + assertThat(context.getAllReferencedBuildConfigs()).isEmpty(); + assertThat(context.getAllReferencingBuildConfigs()).containsExactly(project0.getActiveBuildConfig()); // Change the active configuration of project1, and test that two configurations are built ContextBuilder.clearStats(); @@ -299,8 +295,8 @@ public void testReferenceVariantTwice() throws CoreException { ContextBuilder.assertValid(); context = ContextBuilder.getContext(project0.getActiveBuildConfig()); - assertThat(context.getAllReferencedBuildConfigs(), arrayContaining(project1PreviousActive, project1NewActive)); - assertThat(context.getAllReferencingBuildConfigs(), emptyArray()); - assertThat(context.getRequestedConfigs(), arrayContaining(project0.getActiveBuildConfig())); + assertThat(context.getAllReferencedBuildConfigs()).containsExactly(project1PreviousActive, project1NewActive); + assertThat(context.getAllReferencingBuildConfigs()).isEmpty(); + assertThat(context.getRequestedConfigs()).containsExactly(project0.getActiveBuildConfig()); } } diff --git a/resources/tests/org.eclipse.core.tests.resources/src/org/eclipse/core/tests/internal/builders/BuilderNatureTest.java b/resources/tests/org.eclipse.core.tests.resources/src/org/eclipse/core/tests/internal/builders/BuilderNatureTest.java index 0eeb571bd67..6d5cd30d79b 100644 --- a/resources/tests/org.eclipse.core.tests.resources/src/org/eclipse/core/tests/internal/builders/BuilderNatureTest.java +++ b/resources/tests/org.eclipse.core.tests.resources/src/org/eclipse/core/tests/internal/builders/BuilderNatureTest.java @@ -13,15 +13,13 @@ *******************************************************************************/ package org.eclipse.core.tests.internal.builders; +import static org.assertj.core.api.Assertions.assertThat; import static org.eclipse.core.tests.resources.ResourceTestPluginConstants.NATURE_SNOW; import static org.eclipse.core.tests.resources.ResourceTestPluginConstants.NATURE_WATER; import static org.eclipse.core.tests.resources.ResourceTestUtil.createInWorkspace; import static org.eclipse.core.tests.resources.ResourceTestUtil.createTestMonitor; import static org.eclipse.core.tests.resources.ResourceTestUtil.setAutoBuilding; import static org.eclipse.core.tests.resources.ResourceTestUtil.waitForBuild; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.not; import static org.junit.Assert.assertTrue; import java.io.ByteArrayInputStream; @@ -140,7 +138,7 @@ public void testMissingNature() throws CoreException { //make sure the build spec doesn't include snow builder ICommand[] commands = project.getDescription().getBuildSpec(); for (ICommand command : commands) { - assertThat(command.getBuilderName(), not(is(SnowBuilder.BUILDER_NAME))); + assertThat(command.getBuilderName()).isNotEqualTo(SnowBuilder.BUILDER_NAME); } //now add the snow nature back and ensure snow builder runs @@ -167,7 +165,7 @@ public void testMissingNature() throws CoreException { //make sure the build spec doesn't include snow builder commands = project.getDescription().getBuildSpec(); for (ICommand command : commands) { - assertThat(command.getBuilderName(), not(is(SnowBuilder.BUILDER_NAME))); + assertThat(command.getBuilderName()).isNotEqualTo(SnowBuilder.BUILDER_NAME); } //now re-enable the nature and ensure that the delta was null diff --git a/resources/tests/org.eclipse.core.tests.resources/src/org/eclipse/core/tests/internal/builders/ContextBuilder.java b/resources/tests/org.eclipse.core.tests.resources/src/org/eclipse/core/tests/internal/builders/ContextBuilder.java index 10c1c4569ee..9e1c6fa7178 100644 --- a/resources/tests/org.eclipse.core.tests.resources/src/org/eclipse/core/tests/internal/builders/ContextBuilder.java +++ b/resources/tests/org.eclipse.core.tests.resources/src/org/eclipse/core/tests/internal/builders/ContextBuilder.java @@ -13,8 +13,7 @@ *******************************************************************************/ package org.eclipse.core.tests.internal.builders; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.is; +import static org.assertj.core.api.Assertions.assertThat; import java.util.HashMap; import java.util.Map; @@ -62,8 +61,9 @@ public static IBuildContext getContext(IBuildConfiguration variant) { public static void assertValid() { for (ContextBuilder builder : builders.values()) { if (builder.getRuleCalledForLastBuild) { - assertThat(builder.contextForLastBuild, is(builder.contextForLastBuildInGetRule)); - assertThat(builder.buildConfigurationForLastBuild, is(builder.buildConfigurationForLastBuildInGetRule)); + assertThat(builder.contextForLastBuild).isEqualTo(builder.contextForLastBuildInGetRule); + assertThat(builder.buildConfigurationForLastBuild) + .isEqualTo(builder.buildConfigurationForLastBuildInGetRule); } } } diff --git a/resources/tests/org.eclipse.core.tests.resources/src/org/eclipse/core/tests/internal/builders/CustomBuildTriggerTest.java b/resources/tests/org.eclipse.core.tests.resources/src/org/eclipse/core/tests/internal/builders/CustomBuildTriggerTest.java index 4dfc2d238af..6450790b5a0 100644 --- a/resources/tests/org.eclipse.core.tests.resources/src/org/eclipse/core/tests/internal/builders/CustomBuildTriggerTest.java +++ b/resources/tests/org.eclipse.core.tests.resources/src/org/eclipse/core/tests/internal/builders/CustomBuildTriggerTest.java @@ -12,14 +12,13 @@ ******************************************************************************/ package org.eclipse.core.tests.internal.builders; +import static org.assertj.core.api.Assertions.assertThat; import static org.eclipse.core.resources.ResourcesPlugin.getWorkspace; import static org.eclipse.core.tests.resources.ResourceTestUtil.createRandomContentsStream; import static org.eclipse.core.tests.resources.ResourceTestUtil.createTestMonitor; import static org.eclipse.core.tests.resources.ResourceTestUtil.setAutoBuilding; import static org.eclipse.core.tests.resources.ResourceTestUtil.updateProjectDescription; import static org.eclipse.core.tests.resources.ResourceTestUtil.waitForBuild; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.arrayWithSize; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; @@ -230,7 +229,7 @@ public void testConfigurable() throws CoreException { updateProjectDescription(project).addingCommand(CustomTriggerBuilder.BUILDER_NAME).withTestBuilderId("Build0") .apply(); - assertThat(project.getDescription().getBuildSpec(), arrayWithSize(1)); + assertThat(project.getDescription().getBuildSpec()).hasSize(1); ICommand command = project.getDescription().getBuildSpec()[0]; assertTrue("1.0", command.isConfigurable()); //ensure that setBuilding has effect @@ -309,7 +308,7 @@ public void testNonConfigurable() throws CoreException { // Create and set a build specs for project updateProjectDescription(project).addingCommand(SortBuilder.BUILDER_NAME).withTestBuilderId("Build0").apply(); - assertThat(project.getDescription().getBuildSpec(), arrayWithSize(1)); + assertThat(project.getDescription().getBuildSpec()).hasSize(1); ICommand command = project.getDescription().getBuildSpec()[0]; assertTrue("1.0", !command.isConfigurable()); //ensure that setBuilding has no effect @@ -357,7 +356,7 @@ public void testSkipAutobuildDelta() throws CoreException { updateProjectDescription(project).addingCommand(CustomTriggerBuilder.BUILDER_NAME).withTestBuilderId("Build0") .withBuildingSetting(IncrementalProjectBuilder.AUTO_BUILD, false) .apply(); - assertThat(project.getDescription().getBuildSpec(), arrayWithSize(1)); + assertThat(project.getDescription().getBuildSpec()).hasSize(1); ICommand command = project.getDescription().getBuildSpec()[0]; // turn autobuild back on diff --git a/resources/tests/org.eclipse.core.tests.resources/src/org/eclipse/core/tests/internal/builders/ParallelBuildChainTest.java b/resources/tests/org.eclipse.core.tests.resources/src/org/eclipse/core/tests/internal/builders/ParallelBuildChainTest.java index 26b128d6a8f..0001f00086a 100644 --- a/resources/tests/org.eclipse.core.tests.resources/src/org/eclipse/core/tests/internal/builders/ParallelBuildChainTest.java +++ b/resources/tests/org.eclipse.core.tests.resources/src/org/eclipse/core/tests/internal/builders/ParallelBuildChainTest.java @@ -13,6 +13,7 @@ *******************************************************************************/ package org.eclipse.core.tests.internal.builders; +import static org.assertj.core.api.Assertions.assertThat; import static org.eclipse.core.resources.ResourcesPlugin.getWorkspace; import static org.eclipse.core.tests.resources.ResourceTestPluginConstants.PI_RESOURCES_TESTS; import static org.eclipse.core.tests.resources.ResourceTestUtil.createInWorkspace; @@ -21,13 +22,6 @@ import static org.eclipse.core.tests.resources.ResourceTestUtil.updateProjectDescription; import static org.eclipse.core.tests.resources.ResourceTestUtil.waitForBuild; import static org.eclipse.core.tests.resources.TestUtil.waitForCondition; -import static org.hamcrest.CoreMatchers.not; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.containsInAnyOrder; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.hasItems; -import static org.hamcrest.number.OrderingComparison.greaterThanOrEqualTo; -import static org.hamcrest.number.OrderingComparison.lessThanOrEqualTo; import java.util.ArrayList; import java.util.Arrays; @@ -228,9 +222,10 @@ public void testWorkspaceBuild_ConflictingRule() throws Exception { executeIncrementalWorkspaceBuild(() -> { waitForCondition(() -> TimerBuilder.getStartedProjectBuilds().size() > 1, millisToWaitForUnexpectedParallelBuild); - assertThat( - "all build jobs have started in time although infinitely running builds with conflicting rules exist", - TimerBuilder.getStartedProjectBuilds(), not(containsInAnyOrder(longRunningProjects))); + assertThat(longRunningProjects).withFailMessage( + "all build jobs have started in time although infinitely running builds with conflicting rules exist") + .anySatisfy(longRunningProject -> assertThat(TimerBuilder.getStartedProjectBuilds()) + .doesNotContain(longRunningProject)); assertMaximumNumberOfSimultaneousBuilds(1); }); } @@ -469,25 +464,27 @@ protected IStatus run(IProgressMonitor monitor) { } private void assertMinimumNumberOfSimultaneousBuilds(int minimumNumberOfSimulaneousBuilds) { - assertThat("too few builds have run in parallel", TimerBuilder.getMaximumNumberOfSimultaneousBuilds(), - greaterThanOrEqualTo(minimumNumberOfSimulaneousBuilds)); + assertThat(TimerBuilder.getMaximumNumberOfSimultaneousBuilds()) + .as("check maximum number of parallel builds exceeds minimum expected number") + .isGreaterThanOrEqualTo(minimumNumberOfSimulaneousBuilds); } private void assertMaximumNumberOfSimultaneousBuilds(int maximumNumberOfSimulaneousBuilds) { - assertThat("too many builds have run in parallel", TimerBuilder.getMaximumNumberOfSimultaneousBuilds(), - lessThanOrEqualTo(maximumNumberOfSimulaneousBuilds)); + assertThat(TimerBuilder.getMaximumNumberOfSimultaneousBuilds()) + .as("check maximum number of parallel builds does not exceed maximum expected number") + .isLessThanOrEqualTo(maximumNumberOfSimulaneousBuilds); } private void assertMaximumNumberOfConcurrentWorkspaceBuilds() { - assertThat("too many workspace builds have run in parallel", - TimerBuilder.getMaximumNumberOfSimultaneousBuilds(), - lessThanOrEqualTo(getWorkspace().getDescription().getMaxConcurrentBuilds())); + assertThat(TimerBuilder.getMaximumNumberOfSimultaneousBuilds()) + .as("check maximum number of parallel builds does not exceed workspace limit") + .isLessThanOrEqualTo(getWorkspace().getDescription().getMaxConcurrentBuilds()); } private void assertBuildsToStart(List projects) { waitForCondition(() -> TimerBuilder.getStartedProjectBuilds().containsAll(projects), TIMEOUT_IN_MILLIS); - assertThat("not all build jobs have started in time", TimerBuilder.getStartedProjectBuilds(), - hasItems(projects.toArray(IProject[]::new))); + assertThat(TimerBuilder.getStartedProjectBuilds()).as("check all build jobs have started in time") + .containsAll(projects); } private static class ExpectedExecutionTime { @@ -503,8 +500,9 @@ private long getExecutionTimeInMillis() { } void assertMinimumExecutionTimeReached() { - assertThat("build was faster than the expected execution time (in milliseconds)", - getExecutionTimeInMillis(), greaterThanOrEqualTo(minimumExecutionTimeInMillis)); + assertThat(getExecutionTimeInMillis()) + .as("check build was not faster than the expected execution time (in milliseconds)") + .isGreaterThanOrEqualTo(minimumExecutionTimeInMillis); } static ExpectedExecutionTime captureFromCurrentTime(int minimumExecutionTimeInMillis) { @@ -514,13 +512,13 @@ static ExpectedExecutionTime captureFromCurrentTime(int minimumExecutionTimeInMi private void assertBuildsToFinish(List projects) { waitForCondition(() -> TimerBuilder.getFinishedProjectBuilds().containsAll(projects), TIMEOUT_IN_MILLIS); - assertThat("not all build jobs have finished in time", TimerBuilder.getFinishedProjectBuilds(), - hasItems(projects.toArray(IProject[]::new))); + assertThat(TimerBuilder.getFinishedProjectBuilds()).as("check all build jobs have finished in time") + .containsAll(projects); } private void assertSequentialBuildEventsForProjects(Iterable projects) { - assertThat("unexpected order of build events occurred", TimerBuilder.getBuildEvents(), - equalTo(getExpectedSequentialBuildEvents(projects))); + assertThat(TimerBuilder.getBuildEvents()).as("order of build events") + .isEqualTo(getExpectedSequentialBuildEvents(projects)); } private Iterable getExpectedSequentialBuildEvents(Iterable projects) { diff --git a/resources/tests/org.eclipse.core.tests.resources/src/org/eclipse/core/tests/internal/builders/RelaxedSchedRuleBuilderTest.java b/resources/tests/org.eclipse.core.tests.resources/src/org/eclipse/core/tests/internal/builders/RelaxedSchedRuleBuilderTest.java index 78c589dfbc8..cbca8c93408 100644 --- a/resources/tests/org.eclipse.core.tests.resources/src/org/eclipse/core/tests/internal/builders/RelaxedSchedRuleBuilderTest.java +++ b/resources/tests/org.eclipse.core.tests.resources/src/org/eclipse/core/tests/internal/builders/RelaxedSchedRuleBuilderTest.java @@ -14,15 +14,13 @@ *******************************************************************************/ package org.eclipse.core.tests.internal.builders; +import static org.assertj.core.api.Assertions.assertThat; import static org.eclipse.core.resources.ResourcesPlugin.getWorkspace; import static org.eclipse.core.tests.resources.ResourceTestUtil.createInWorkspace; import static org.eclipse.core.tests.resources.ResourceTestUtil.createTestMonitor; import static org.eclipse.core.tests.resources.ResourceTestUtil.setAutoBuilding; import static org.eclipse.core.tests.resources.ResourceTestUtil.updateProjectDescription; import static org.eclipse.core.tests.resources.ResourceTestUtil.waitForEncodingRelatedJobs; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.empty; -import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; @@ -631,8 +629,8 @@ public void assertNoErrorsLogged() { loggedErrors.removeIf(errors::add); List thrownExceptions = errors.stream().map(IStatus::getException).filter(Objects::nonNull) .collect(Collectors.toList()); - assertThat("Test logged exceptions", thrownExceptions, is(empty())); - assertThat("Test logged errors", errors, is(empty())); + assertThat(thrownExceptions).as("logged exceptions").isEmpty(); + assertThat(errors).as("logged errors").isEmpty(); } } diff --git a/resources/tests/org.eclipse.core.tests.resources/src/org/eclipse/core/tests/internal/events/BuildProjectFromMultipleJobsTest.java b/resources/tests/org.eclipse.core.tests.resources/src/org/eclipse/core/tests/internal/events/BuildProjectFromMultipleJobsTest.java index 85fcc6f2eeb..0371ea0c8d2 100644 --- a/resources/tests/org.eclipse.core.tests.resources/src/org/eclipse/core/tests/internal/events/BuildProjectFromMultipleJobsTest.java +++ b/resources/tests/org.eclipse.core.tests.resources/src/org/eclipse/core/tests/internal/events/BuildProjectFromMultipleJobsTest.java @@ -13,14 +13,12 @@ *******************************************************************************/ package org.eclipse.core.tests.internal.events; +import static org.assertj.core.api.Assertions.assertThat; import static org.eclipse.core.resources.ResourcesPlugin.getWorkspace; import static org.eclipse.core.tests.resources.ResourceTestPluginConstants.PI_RESOURCES_TESTS; import static org.eclipse.core.tests.resources.ResourceTestUtil.createInWorkspace; import static org.eclipse.core.tests.resources.ResourceTestUtil.setAutoBuilding; import static org.eclipse.core.tests.resources.ResourceTestUtil.updateProjectDescription; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.hasSize; -import static org.hamcrest.Matchers.instanceOf; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; @@ -133,18 +131,18 @@ public void testBuildersAreNotModifiable() throws Exception { // Get a non-cloned version of the project desc build spec BuildCommand buildCommand = (BuildCommand) project.internalGetDescription().getBuildSpec(false)[0]; - assertThat(buildCommand.getBuilders(), instanceOf(Map.class)); + assertThat(buildCommand.getBuilders()).isInstanceOf(Map.class); if (buildCommand.getBuilders() instanceof Map buildersMap) { - assertThat(buildersMap.entrySet(), hasSize(1)); + assertThat(buildersMap.entrySet()).hasSize(1); // Try to change the internal data buildersMap.clear(); - assertThat(buildersMap.entrySet(), hasSize(0)); + assertThat(buildersMap.entrySet()).isEmpty(); } - assertThat(buildCommand.getBuilders(), instanceOf(Map.class)); + assertThat(buildCommand.getBuilders()).isInstanceOf(Map.class); if (buildCommand.getBuilders() instanceof Map buildersMap) { // Should still be OK - assertThat("BuildCommand state was changed!", buildersMap.entrySet(), hasSize(1)); + assertThat(buildersMap.entrySet()).as("check BuildCommand state did not changed").hasSize(1); } } diff --git a/resources/tests/org.eclipse.core.tests.resources/src/org/eclipse/core/tests/internal/localstore/CopyTest.java b/resources/tests/org.eclipse.core.tests.resources/src/org/eclipse/core/tests/internal/localstore/CopyTest.java index 4aeb3d789bb..76ab8cdcbfa 100644 --- a/resources/tests/org.eclipse.core.tests.resources/src/org/eclipse/core/tests/internal/localstore/CopyTest.java +++ b/resources/tests/org.eclipse.core.tests.resources/src/org/eclipse/core/tests/internal/localstore/CopyTest.java @@ -13,15 +13,12 @@ *******************************************************************************/ package org.eclipse.core.tests.internal.localstore; +import static org.assertj.core.api.Assertions.assertThat; import static org.eclipse.core.resources.ResourcesPlugin.getWorkspace; import static org.eclipse.core.tests.resources.ResourceTestUtil.createInFileSystem; import static org.eclipse.core.tests.resources.ResourceTestUtil.createInWorkspace; import static org.eclipse.core.tests.resources.ResourceTestUtil.removeFromFileSystem; import static org.eclipse.core.tests.resources.ResourceTestUtil.removeFromWorkspace; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.arrayWithSize; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.not; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertThrows; import static org.junit.Assert.assertTrue; @@ -79,8 +76,7 @@ public void testCopyResource() throws Throwable { for (int i = 0; i < NUMBER_OF_PROPERTIES; i++) { String persistentValue = destination.getPersistentProperty(propNames[i]); Object sessionValue = destination.getSessionProperty(propNames[i]); - assertThat(propValues[i], is(persistentValue)); - assertThat(propValues[i], is(not((sessionValue)))); + assertThat(propValues[i]).isEqualTo(persistentValue).isNotEqualTo(sessionValue); } removeFromWorkspace(destination); removeFromFileSystem(destination); @@ -95,8 +91,7 @@ public void testCopyResource() throws Throwable { for (int i = 0; i < NUMBER_OF_PROPERTIES; i++) { String persistentValue = destinationInFolder.getPersistentProperty(propNames[i]); Object sessionValue = destinationInFolder.getSessionProperty(propNames[i]); - assertThat(propValues[i], is(persistentValue)); - assertThat(propValues[i], is(not(sessionValue))); + assertThat(propValues[i]).isEqualTo(persistentValue).isNotEqualTo(sessionValue); } removeFromWorkspace(destinationInFolder); removeFromFileSystem(destinationInFolder); @@ -114,7 +109,7 @@ public void testCopyResource() throws Throwable { IFolder destinationFolder = project.getFolder("destination"); CoreException exception = assertThrows(CoreException.class, () -> folder.copy(destinationFolder.getFullPath(), false, null)); - assertThat(exception.getStatus().getChildren(), arrayWithSize(2)); + assertThat(exception.getStatus().getChildren()).hasSize(2); assertTrue(destinationFolder.exists()); assertTrue(((IContainer) destinationFolder).getFile(IPath.fromOSString(file.getName())).exists()); assertFalse(((IContainer) destinationFolder).getFolder(IPath.fromOSString(subfolder.getName())).exists()); @@ -124,8 +119,7 @@ public void testCopyResource() throws Throwable { for (int i = 0; i < NUMBER_OF_PROPERTIES; i++) { String persistentValue = target.getPersistentProperty(propNames[i]); Object sessionValue = target.getSessionProperty(propNames[i]); - assertThat(propValues[i], is(persistentValue)); - assertThat(propValues[i], is(not(sessionValue))); + assertThat(propValues[i]).isEqualTo(persistentValue).isNotEqualTo(sessionValue); } removeFromWorkspace(destinationFolder); removeFromFileSystem(destinationFolder); diff --git a/resources/tests/org.eclipse.core.tests.resources/src/org/eclipse/core/tests/internal/localstore/SafeChunkyInputOutputStreamTest.java b/resources/tests/org.eclipse.core.tests.resources/src/org/eclipse/core/tests/internal/localstore/SafeChunkyInputOutputStreamTest.java index b3b1264aa3d..756b294ad7f 100644 --- a/resources/tests/org.eclipse.core.tests.resources/src/org/eclipse/core/tests/internal/localstore/SafeChunkyInputOutputStreamTest.java +++ b/resources/tests/org.eclipse.core.tests.resources/src/org/eclipse/core/tests/internal/localstore/SafeChunkyInputOutputStreamTest.java @@ -13,11 +13,10 @@ *******************************************************************************/ package org.eclipse.core.tests.internal.localstore; +import static org.assertj.core.api.Assertions.assertThat; import static org.eclipse.core.tests.harness.FileSystemHelper.getRandomLocation; import static org.eclipse.core.tests.resources.ResourceTestUtil.createRandomString; import static org.eclipse.core.tests.resources.ResourceTestUtil.removeFromFileSystem; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertThrows; @@ -94,7 +93,7 @@ public void testBufferLimit() throws Exception { try (SafeChunkyInputStream input = new SafeChunkyInputStream(target)) { byte[] read = new byte[chunk.length]; assertEquals(chunk.length, input.read(read)); - assertThat(read, is(chunk)); + assertThat(read).isEqualTo(chunk); } Workspace.clear(target); // make sure there was nothing here before } @@ -175,13 +174,13 @@ public void testFailure() throws Exception { assertEquals(chunk4.length, input.read(read4)); assertEquals(chunk5.length, input.read(read5)); assertEquals((fakeEnd.length + chunk6.length), input.read(read6)); - assertThat(read1, is(chunk1)); + assertThat(read1).isEqualTo(chunk1); // assert("3.7", compare(chunk2, read2)); - assertThat(read3, is(chunk3)); - assertThat(read4, is(chunk4)); - assertThat(read5, is(chunk5)); + assertThat(read3).isEqualTo(chunk3); + assertThat(read4).isEqualTo(chunk4); + assertThat(read5).isEqualTo(chunk5); byte[] expected = merge(fakeEnd, chunk6); - assertThat(read6, is(expected)); + assertThat(read6).isEqualTo(expected); } } @@ -245,11 +244,11 @@ public void testSimple() throws Exception { assertEquals(chunk3.length, input.read(read3)); assertEquals(chunk4.length, input.read(read4)); assertEquals(chunk5.length, input.read(read5)); - assertThat(read1, is(chunk1)); - assertThat(read2, is(chunk2)); - assertThat(read3, is(chunk3)); - assertThat(read4, is(chunk4)); - assertThat(read5, is(chunk5)); + assertThat(read1).isEqualTo(chunk1); + assertThat(read2).isEqualTo(chunk2); + assertThat(read3).isEqualTo(chunk3); + assertThat(read4).isEqualTo(chunk4); + assertThat(read5).isEqualTo(chunk5); } finally { Workspace.clear(target); // make sure there was nothing here before } diff --git a/resources/tests/org.eclipse.core.tests.resources/src/org/eclipse/core/tests/internal/resources/ModelObjectReaderWriterTest.java b/resources/tests/org.eclipse.core.tests.resources/src/org/eclipse/core/tests/internal/resources/ModelObjectReaderWriterTest.java index a1bfce30d46..6e63365af0c 100644 --- a/resources/tests/org.eclipse.core.tests.resources/src/org/eclipse/core/tests/internal/resources/ModelObjectReaderWriterTest.java +++ b/resources/tests/org.eclipse.core.tests.resources/src/org/eclipse/core/tests/internal/resources/ModelObjectReaderWriterTest.java @@ -15,21 +15,13 @@ *******************************************************************************/ package org.eclipse.core.tests.internal.resources; +import static org.assertj.core.api.Assertions.assertThat; import static org.eclipse.core.resources.ResourcesPlugin.getWorkspace; import static org.eclipse.core.tests.harness.FileSystemHelper.getRandomLocation; import static org.eclipse.core.tests.harness.FileSystemHelper.getTempDir; import static org.eclipse.core.tests.resources.ResourceTestUtil.createInputStream; import static org.eclipse.core.tests.resources.ResourceTestUtil.createTestMonitor; import static org.eclipse.core.tests.resources.ResourceTestUtil.removeFromFileSystem; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.anEmptyMap; -import static org.hamcrest.Matchers.arrayWithSize; -import static org.hamcrest.Matchers.emptyArray; -import static org.hamcrest.Matchers.emptyString; -import static org.hamcrest.Matchers.hasSize; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.not; -import static org.hamcrest.Matchers.nullValue; import java.io.ByteArrayOutputStream; import java.io.FileOutputStream; @@ -184,36 +176,36 @@ private HashMap buildBaselineDescriptors() { private void compareBuildSpecs(ICommand[] commands, ICommand[] commands2) { // ASSUMPTION: commands and commands2 are non-null - assertThat("different number of commands", commands, arrayWithSize(commands2.length)); + assertThat(commands).as("compare number of commands").hasSameSizeAs(commands2); for (int i = 0; i < commands.length; i++) { - assertThat("names of builders at index " + i + " are different", commands[i].getBuilderName(), - is(commands2[i].getBuilderName())); + assertThat(commands[i].getBuilderName()).as("compare names of builders at index %s", i) + .isEqualTo(commands2[i].getBuilderName()); Map args = commands[i].getArguments(); Map args2 = commands2[i].getArguments(); - assertThat("different number of arguments for builder at index " + i, args.entrySet(), - hasSize(args2.size())); + assertThat(args.entrySet()).as("compare number of arguments for builder at index %s", i) + .hasSize(args2.size()); for (Entry entry : args.entrySet()) { String key = entry.getKey(); String value = entry.getValue(); String value2 = args2.get(key); if (value == null) { - assertThat("value for key '" + key + "' should be null", value2, nullValue()); + assertThat(value2).as("value for key '%s'", key).isNull(); } else { - assertThat("unequal values for key: " + key, args.get(key), is(args2.get(key))); + assertThat(args.get(key)).as("compare values for key: %s", key).isEqualTo(args2.get(key)); } } } } private void compareProjectDescriptions(int errorTag, ProjectDescription description, ProjectDescription description2) { - assertThat(description.getName(), is(description2.getName())); + assertThat(description.getName()).isEqualTo(description2.getName()); String comment = description.getComment(); if (comment == null) { // The old reader previously returned null for an empty comment. We // are changing this so it now returns an empty string. - assertThat(description2.getComment(), emptyString()); + assertThat(description2.getComment()).isEmpty(); } else { - assertThat(description.getComment(), is(description2.getComment())); + assertThat(description.getComment()).isEqualTo(description2.getComment()); } IProject[] projects = description.getReferencedProjects(); @@ -226,19 +218,19 @@ private void compareProjectDescriptions(int errorTag, ProjectDescription descrip String[] natures = description.getNatureIds(); String[] natures2 = description2.getNatureIds(); - assertThat(natures, is(natures2)); + assertThat(natures).isEqualTo(natures2); HashMap links = description.getLinks(); HashMap links2 = description2.getLinks(); - assertThat(links, is(links2)); + assertThat(links).isEqualTo(links2); } private void compareProjects(IProject[] projects, IProject[] projects2) { // ASSUMPTION: projects and projects2 are non-null - assertThat("different number of projects", projects, arrayWithSize(projects2.length)); + assertThat(projects).as("compare number of projects").hasSameSizeAs(projects2); for (int i = 0; i < projects.length; i++) { - assertThat("names of projects at index " + i + " are different", projects[i].getName(), - is(projects2[i].getName())); + assertThat(projects[i].getName()).as("compare names of projects at index %s", i) + .isEqualTo(projects2[i].getName()); } } @@ -326,7 +318,7 @@ public void testConsistentWrite() throws Throwable { String result = buffer.toString(); // order of keys in serialized file should be exactly the same as expected - assertThat(result, is(expected)); + assertThat(result).isEqualTo(expected); } @Test @@ -345,7 +337,7 @@ public void testInvalidProjectDescription1() throws Throwable { createInputStream(invalidProjectDescription).transferTo(output); } ProjectDescription projDesc = reader.read(location); - assertThat(projDesc, nullValue()); + assertThat(projDesc).isNull(); } @Test @@ -358,14 +350,14 @@ public void testInvalidProjectDescription2() throws Throwable { createInputStream(invalidProjectDescription).transferTo(output); } ProjectDescription projDesc = readDescription(store); - assertThat(projDesc, not(nullValue())); - assertThat(projDesc.getName(), nullValue()); - assertThat(projDesc.getComment(), emptyString()); - assertThat(projDesc.getLocationURI(), nullValue()); - assertThat(projDesc.getReferencedProjects(), emptyArray()); - assertThat(projDesc.getNatureIds(), emptyArray()); - assertThat(projDesc.getBuildSpec(), emptyArray()); - assertThat(projDesc.getLinks(), nullValue()); + assertThat(projDesc).isNotNull(); + assertThat(projDesc.getName()).isNull(); + assertThat(projDesc.getComment()).isEmpty(); + assertThat(projDesc.getLocationURI()).isNull(); + assertThat(projDesc.getReferencedProjects()).isEmpty(); + assertThat(projDesc.getNatureIds()).isEmpty(); + assertThat(projDesc.getBuildSpec()).isEmpty(); + assertThat(projDesc.getLinks()).isNull(); } @Test @@ -379,14 +371,14 @@ public void testInvalidProjectDescription3() throws Throwable { } ProjectDescription projDesc = readDescription(store); - assertThat(projDesc, not(nullValue())); - assertThat(projDesc.getName(), is("abc")); - assertThat(projDesc.getComment(), emptyString()); - assertThat(projDesc.getLocationURI(), nullValue()); - assertThat(projDesc.getReferencedProjects(), emptyArray()); - assertThat(projDesc.getNatureIds(), emptyArray()); - assertThat(projDesc.getBuildSpec(), emptyArray()); - assertThat(projDesc.getLinks(), nullValue()); + assertThat(projDesc).isNotNull(); + assertThat(projDesc.getName()).isEqualTo("abc"); + assertThat(projDesc.getComment()).isEmpty(); + assertThat(projDesc.getLocationURI()).isNull(); + assertThat(projDesc.getReferencedProjects()).isEmpty(); + assertThat(projDesc.getNatureIds()).isEmpty(); + assertThat(projDesc.getBuildSpec()).isEmpty(); + assertThat(projDesc.getLinks()).isNull(); } @Test @@ -399,16 +391,16 @@ public void testInvalidProjectDescription4() throws Throwable { createInputStream(invalidProjectDescription).transferTo(output); } ProjectDescription projDesc = readDescription(store); - assertThat(projDesc, not(nullValue())); - assertThat(projDesc.getName(), is("abc")); - assertThat(projDesc.getComment(), emptyString()); - assertThat(projDesc.getLocationURI(), nullValue()); - assertThat(projDesc.getReferencedProjects(), emptyArray()); - assertThat(projDesc.getNatureIds(), emptyArray()); - assertThat(projDesc.getBuildSpec(), emptyArray()); + assertThat(projDesc).isNotNull(); + assertThat(projDesc.getName()).isEqualTo("abc"); + assertThat(projDesc.getComment()).isEmpty(); + assertThat(projDesc.getLocationURI()).isNull(); + assertThat(projDesc.getReferencedProjects()).isEmpty(); + assertThat(projDesc.getNatureIds()).isEmpty(); + assertThat(projDesc.getBuildSpec()).isEmpty(); LinkDescription link = projDesc.getLinks().values().iterator().next(); - assertThat(link.getProjectRelativePath(), is(IPath.fromOSString("newLink"))); - assertThat(URIUtil.toPath(link.getLocationURI()).toString(), is(PATH_STRING)); + assertThat(link.getProjectRelativePath()).isEqualTo(IPath.fromOSString("newLink")); + assertThat(URIUtil.toPath(link.getLocationURI()).toString()).isEqualTo(PATH_STRING); } /** @@ -430,8 +422,9 @@ public void testLongProjectDescription() throws Throwable { ProjectDescription projDesc = reader.read(location); removeFromFileSystem(location.toFile()); for (LinkDescription link : projDesc.getLinks().values()) { - assertThat("Unexpected location URI for link with relative path: " + link.getProjectRelativePath(), - link.getLocationURI(), is(LONG_LOCATION_URI)); + assertThat(link.getLocationURI()) + .as("location URI for link with relative path: %s", link.getProjectRelativePath()) + .isEqualTo(LONG_LOCATION_URI); } } @@ -453,8 +446,9 @@ public void testLongProjectDescriptionURI() throws Throwable { ProjectDescription projDesc = reader.read(location); removeFromFileSystem(location.toFile()); for (LinkDescription link : projDesc.getLinks().values()) { - assertThat("Unexpected location URI for link with relative path: " + link.getProjectRelativePath(), - link.getLocationURI(), is(LONG_LOCATION_URI)); + assertThat(link.getLocationURI()) + .as("location URI for link with relative path: %s", link.getProjectRelativePath()) + .isEqualTo(LONG_LOCATION_URI); } } @@ -532,21 +526,22 @@ public void testProjectDescription() throws Throwable { /* test read */ ProjectDescription description2 = readDescription(tempStore); - assertThat(description.getName(), is(description2.getName())); - assertThat(location, is(description.getLocationURI())); + assertThat(description.getName()).isEqualTo(description2.getName()); + assertThat(location).isEqualTo(description.getLocationURI()); ICommand[] commands2 = description2.getBuildSpec(); - assertThat(commands2, arrayWithSize(2)); - assertThat(commands2[0].getBuilderName(), is("MyCommand")); - assertThat(commands2[0].getArguments().get("ArgOne"), is("ARGH!")); - assertThat(commands2[0].getArguments().get("ArgTwo"), is("2 x ARGH!")); - assertThat(commands2[0].getArguments().get("NullArg"), emptyString()); - assertThat(commands2[0].getArguments().get("EmptyArg"), emptyString()); - assertThat(commands2[1].getBuilderName(), is("MyOtherCommand")); - assertThat(commands2[1].getArguments().get("ArgOne"), is("ARGH!")); - assertThat(commands2[1].getArguments().get("ArgTwo"), is("2 x ARGH!")); - assertThat(commands2[0].getArguments().get("NullArg"), emptyString()); - assertThat(commands2[0].getArguments().get("EmptyArg"), emptyString()); + assertThat(commands2).hasSize(2).satisfiesExactly(first -> { + assertThat(first.getBuilderName()).isEqualTo("MyCommand"); + assertThat(first.getArguments().get("ArgOne")).isEqualTo("ARGH!"); + assertThat(first.getArguments().get("ArgTwo")).isEqualTo("2 x ARGH!"); + assertThat(first.getArguments().get("NullArg")).isEmpty(); + assertThat(first.getArguments().get("EmptyArg")).isEmpty(); + assertThat(first.getArguments().get("NullArg")).isEmpty(); + assertThat(first.getArguments().get("EmptyArg").isEmpty()); + }, second -> { + assertThat(second.getBuilderName()).isEqualTo("MyOtherCommand"); + assertThat(second.getArguments().get("ArgOne")).isEqualTo("ARGH!"); + }); } @Test @@ -588,22 +583,23 @@ public void testProjectDescription2() throws Throwable { description2 = reader.read(in); } - assertThat(description.getName(), is(description2.getName())); - assertThat(location, is(description.getLocationURI())); + assertThat(description.getName()).isEqualTo(description2.getName()); + assertThat(location).isEqualTo(description.getLocationURI()); ICommand[] commands2 = description2.getBuildSpec(); - assertThat(commands2, arrayWithSize(1)); - assertThat(commands2[0].getBuilderName(), is("MyCommand")); - assertThat(commands2[0].getArguments().get("ArgOne"), is("ARGH!")); + assertThat(commands2).hasSize(1).satisfiesExactly(command -> { + assertThat(command.getBuilderName()).isEqualTo("MyCommand"); + assertThat(command.getArguments().get("ArgOne")).isEqualTo("ARGH!"); + }); - assertThat(description.getComment(), is(description2.getComment())); + assertThat(description.getComment()).isEqualTo(description2.getComment()); IProject[] ref = description.getReferencedProjects(); IProject[] ref2 = description2.getReferencedProjects(); - assertThat(ref2, arrayWithSize(3)); - assertThat(ref[0].getName(), is(ref2[0].getName())); - assertThat(ref[1].getName(), is(ref2[1].getName())); - assertThat(ref[2].getName(), is(ref2[2].getName())); + assertThat(ref2).hasSize(3).satisfiesExactly( + first -> assertThat(first.getName()).isEqualTo(ref[0].getName()), + second -> assertThat(second.getName()).isEqualTo(ref[1].getName()), + third -> assertThat(third.getName()).isEqualTo(ref[2].getName())); } // see bug 274437 @@ -625,13 +621,14 @@ public void testProjectDescription3() throws Throwable { /* test read */ ProjectDescription description2 = readDescription(tempStore); - assertThat(description.getName(), is(description2.getName())); - assertThat(description.getLocationURI(), is(location)); + assertThat(description.getName()).isEqualTo(description2.getName()); + assertThat(description.getLocationURI()).isEqualTo(location); ICommand[] commands2 = description2.getBuildSpec(); - assertThat(commands2, arrayWithSize(1)); - assertThat(commands2[0].getBuilderName(), is("MyCommand")); - assertThat(commands2[0].getArguments(), anEmptyMap()); + assertThat(commands2).hasSize(1).satisfiesExactly(command -> { + assertThat(command.getBuilderName()).isEqualTo("MyCommand"); + assertThat(command.getArguments()).isEmpty(); + }); } @Test @@ -650,9 +647,9 @@ public void testProjectDescriptionWithSpaces() throws Throwable { /* test read */ ProjectDescription description2 = readDescription(store); - assertThat(description.getName(), is(description2.getName())); - assertThat(description.getLocationURI(), is(location)); - assertThat(description2.getLinkLocationURI(path), is(locationWithSpaces)); + assertThat(description.getName()).isEqualTo(description2.getName()); + assertThat(description.getLocationURI()).isEqualTo(location); + assertThat(description2.getLinkLocationURI(path)).isEqualTo(locationWithSpaces); } protected URI uriFromPortableString(String pathString) { @@ -708,6 +705,6 @@ public void testProjectDescriptionWithFiltersAndNullProject() throws Exception { createInputStream(projectDescription).transferTo(output); } ProjectDescription projDesc = reader.read(location); - assertThat(projDesc, not(nullValue())); + assertThat(projDesc).isNotNull(); } } diff --git a/resources/tests/org.eclipse.core.tests.resources/src/org/eclipse/core/tests/internal/resources/ProjectBuildConfigsTest.java b/resources/tests/org.eclipse.core.tests.resources/src/org/eclipse/core/tests/internal/resources/ProjectBuildConfigsTest.java index d2f0d511a0d..6d2a8af5a8f 100644 --- a/resources/tests/org.eclipse.core.tests.resources/src/org/eclipse/core/tests/internal/resources/ProjectBuildConfigsTest.java +++ b/resources/tests/org.eclipse.core.tests.resources/src/org/eclipse/core/tests/internal/resources/ProjectBuildConfigsTest.java @@ -13,12 +13,10 @@ *******************************************************************************/ package org.eclipse.core.tests.internal.resources; +import static org.assertj.core.api.Assertions.assertThat; import static org.eclipse.core.resources.ResourcesPlugin.getWorkspace; import static org.eclipse.core.tests.resources.ResourceTestUtil.createInWorkspace; import static org.eclipse.core.tests.resources.ResourceTestUtil.createTestMonitor; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.arrayContaining; -import static org.hamcrest.Matchers.is; import org.eclipse.core.internal.resources.BuildConfiguration; import org.eclipse.core.resources.IBuildConfiguration; @@ -64,30 +62,30 @@ public void testBasics() throws CoreException { desc.setBuildConfigs(configs); project.setDescription(desc, createTestMonitor()); - assertThat(project.getBuildConfigs(), arrayContaining(variant0, variant1)); - assertThat(project.getBuildConfig(variantId0), is(variant0)); - assertThat(project.getBuildConfig(variantId1), is(variant1)); + assertThat(project.getBuildConfigs()).containsExactly(variant0, variant1); + assertThat(project.getBuildConfig(variantId0)).isEqualTo(variant0); + assertThat(project.getBuildConfig(variantId1)).isEqualTo(variant1); // Build configuration names don't contribute to equality - assertThat("project '" + project + "' is missing build config: " + variant0, - project.hasBuildConfig(variant0.getName())); - assertThat("project '" + project + "' is missing build config: " + variant1, - project.hasBuildConfig(variant1.getName())); - assertThat("project '" + project + "' unexpectedly has build config: " + variant2, - !project.hasBuildConfig(variant2.getName())); - - assertThat(project.getActiveBuildConfig(), is(variant0)); + assertThat(project.hasBuildConfig(variant0.getName())) + .withFailMessage("project '%s' is missing build config: %s", project, variant0).isTrue(); + assertThat(project.hasBuildConfig(variant1.getName())) + .withFailMessage("project '%s' is missing build config: %s", project, variant1).isTrue(); + assertThat(project.hasBuildConfig(variant2.getName())) + .withFailMessage("project '%s' unexpectedly has build config: %s", project, variant2).isFalse(); + + assertThat(project.getActiveBuildConfig()).isEqualTo(variant0); desc = project.getDescription(); desc.setActiveBuildConfig(variantId1); project.setDescription(desc, createTestMonitor()); - assertThat(project.getActiveBuildConfig(), is(variant1)); + assertThat(project.getActiveBuildConfig()).isEqualTo(variant1); // test that setting the variant to an invalid id has no effect desc.setActiveBuildConfig(variantId2); - assertThat(project.getActiveBuildConfig(), is(variant1)); + assertThat(project.getActiveBuildConfig()).isEqualTo(variant1); IBuildConfiguration variant = project.getBuildConfigs()[0]; - assertThat(variant.getProject(), is(project)); - assertThat(variant.getName(), is(variantId0)); + assertThat(variant.getProject()).isEqualTo(project); + assertThat(variant.getName()).isEqualTo(variantId0); } @Test @@ -95,7 +93,7 @@ public void testDuplicates() throws CoreException { IProjectDescription desc = project.getDescription(); desc.setBuildConfigs(new String[] {variantId0, variantId1, variantId0}); project.setDescription(desc, createTestMonitor()); - assertThat(project.getBuildConfigs(), arrayContaining(variant0, variant1)); + assertThat(project.getBuildConfigs()).containsExactly(variant0, variant1); } @Test @@ -104,15 +102,15 @@ public void testDefaultVariant() throws CoreException { desc.setBuildConfigs(new String[] {}); project.setDescription(desc, createTestMonitor()); - assertThat(project.getBuildConfigs(), arrayContaining(defaultVariant)); - assertThat("project '" + project + "' is missing build config: " + defaultVariant, - project.hasBuildConfig(defaultVariant.getName())); + assertThat(project.getBuildConfigs()).containsExactly(defaultVariant); + assertThat(project.hasBuildConfig(defaultVariant.getName())) + .withFailMessage("project '%s' is missing build config: %s", project, defaultVariant).isTrue(); - assertThat(project.getActiveBuildConfig(), is(defaultVariant)); + assertThat(project.getActiveBuildConfig()).isEqualTo(defaultVariant); desc = project.getDescription(); desc.setActiveBuildConfig(IBuildConfiguration.DEFAULT_CONFIG_NAME); project.setDescription(desc, createTestMonitor()); - assertThat(project.getActiveBuildConfig(), is(defaultVariant)); + assertThat(project.getActiveBuildConfig()).isEqualTo(defaultVariant); } @Test @@ -121,16 +119,16 @@ public void testRemoveActiveVariant() throws CoreException { desc.setBuildConfigs(new String[0]); desc.setBuildConfigs(new String[] {variant0.getName(), variant1.getName()}); project.setDescription(desc, createTestMonitor()); - assertThat(project.getActiveBuildConfig(), is(variant0)); + assertThat(project.getActiveBuildConfig()).isEqualTo(variant0); desc.setBuildConfigs(new String[] {variant0.getName(), variant2.getName()}); project.setDescription(desc, createTestMonitor()); - assertThat(project.getActiveBuildConfig(), is(variant0)); + assertThat(project.getActiveBuildConfig()).isEqualTo(variant0); desc = project.getDescription(); desc.setActiveBuildConfig(variantId2); project.setDescription(desc, createTestMonitor()); desc.setBuildConfigs(new String[] {variant0.getName(), variant1.getName()}); project.setDescription(desc, createTestMonitor()); - assertThat(project.getActiveBuildConfig(), is(variant0)); + assertThat(project.getActiveBuildConfig()).isEqualTo(variant0); } /** @@ -150,12 +148,12 @@ public void testProjectMove() throws CoreException { project.move(desc, false, createTestMonitor()); IProject newProject = getWorkspace().getRoot().getProject(newProjectName); - assertThat("project does not exist: " + newProject, newProject.exists()); + assertThat(newProject).matches(IProject::exists, "exists"); IBuildConfiguration[] newConfigs = newProject.getBuildConfigs(); for (int i = 0; i < configs.length; i++) { - assertThat("unexpected project at index " + i, newConfigs[i].getProject(), is(newProject)); - assertThat("unexpected project name at index " + i, newConfigs[i].getName(), is(configs[i].getName())); + assertThat(newConfigs[i].getProject()).as("project at index %s", i).isEqualTo(newProject); + assertThat(newConfigs[i].getName()).as("project name at index %s", i).isEqualTo(configs[i].getName()); } } diff --git a/resources/tests/org.eclipse.core.tests.resources/src/org/eclipse/core/tests/internal/resources/ProjectDynamicReferencesTest.java b/resources/tests/org.eclipse.core.tests.resources/src/org/eclipse/core/tests/internal/resources/ProjectDynamicReferencesTest.java index 03bf61a1bf7..83e6fb6f664 100644 --- a/resources/tests/org.eclipse.core.tests.resources/src/org/eclipse/core/tests/internal/resources/ProjectDynamicReferencesTest.java +++ b/resources/tests/org.eclipse.core.tests.resources/src/org/eclipse/core/tests/internal/resources/ProjectDynamicReferencesTest.java @@ -13,14 +13,11 @@ *******************************************************************************/ package org.eclipse.core.tests.internal.resources; +import static org.assertj.core.api.Assertions.assertThat; import static org.eclipse.core.resources.ResourcesPlugin.getWorkspace; import static org.eclipse.core.tests.resources.ResourceTestUtil.createInWorkspace; import static org.eclipse.core.tests.resources.ResourceTestUtil.readStringInFileSystem; import static org.eclipse.core.tests.resources.ResourceTestUtil.updateProjectDescription; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.arrayContaining; -import static org.hamcrest.Matchers.emptyArray; -import static org.hamcrest.Matchers.is; import java.util.ArrayList; import java.util.Collections; @@ -76,56 +73,56 @@ public void tearDown() throws Exception { @Test public void testReferencedProjects() throws CoreException { - assertThat("Project0 must not have referenced projects", project0.getReferencedProjects(), emptyArray()); - assertThat("Project1 must not have referenced projects", project1.getReferencedProjects(), emptyArray()); - assertThat("Project2 must not have referenced projects", project2.getReferencedProjects(), emptyArray()); + assertThat(project0.getReferencedProjects()).as("referenced projects of Project0").isEmpty(); + assertThat(project1.getReferencedProjects()).as("referenced projects of Project1").isEmpty(); + assertThat(project2.getReferencedProjects()).as("referenced projects of Project2").isEmpty(); DynamicReferenceProvider.addReference(project0, project1); - assertThat("Project0 must not have referenced projects", project0.getReferencedProjects(), emptyArray()); - assertThat("Project1 must not have referenced projects", project1.getReferencedProjects(), emptyArray()); - assertThat("Project2 must not have referenced projects", project2.getReferencedProjects(), emptyArray()); + assertThat(project0.getReferencedProjects()).as("referenced projects of Project0").isEmpty(); + assertThat(project1.getReferencedProjects()).as("referenced projects of Project1").isEmpty(); + assertThat(project2.getReferencedProjects()).as("referenced projects of Project2").isEmpty(); clearCache(); - assertThat("Project0 must reference Project1", project0.getReferencedProjects(), arrayContaining(project1)); - assertThat("Project1 must not have referenced projects", project1.getReferencedProjects(), emptyArray()); - assertThat("Project2 must not have referenced projects", project2.getReferencedProjects(), emptyArray()); + assertThat(project0.getReferencedProjects()).as("referenced projects of Project0").containsExactly(project1); + assertThat(project1.getReferencedProjects()).as("referenced projects of Project1").isEmpty(); + assertThat(project2.getReferencedProjects()).as("referenced projects of Project2").isEmpty(); DynamicReferenceProvider.addReference(project1, project2); - assertThat("Project0 must reference Project1", project0.getReferencedProjects(), arrayContaining(project1)); - assertThat("Project1 must not have referenced projects", project1.getReferencedProjects(), emptyArray()); - assertThat("Project2 must not have referenced projects", project2.getReferencedProjects(), emptyArray()); + assertThat(project0.getReferencedProjects()).as("referenced projects of Project0").containsExactly(project1); + assertThat(project1.getReferencedProjects()).as("referenced projects of Project1").isEmpty(); + assertThat(project2.getReferencedProjects()).as("referenced projects of Project2").isEmpty(); clearCache(); - assertThat("Project0 must reference Project1", project0.getReferencedProjects(), arrayContaining(project1)); - assertThat("Project1 must reference Project2", project1.getReferencedProjects(), arrayContaining(project2)); - assertThat("Project2 must not have referenced projects", project2.getReferencedProjects(), emptyArray()); + assertThat(project0.getReferencedProjects()).as("referenced projects of Project0").containsExactly(project1); + assertThat(project1.getReferencedProjects()).as("referenced projects of Project1").containsExactly(project2); + assertThat(project2.getReferencedProjects()).as("referenced projects of Project2").isEmpty(); DynamicReferenceProvider.addReference(project0, project2); - assertThat("Project0 must reference Project1", project0.getReferencedProjects(), arrayContaining(project1)); - assertThat("Project1 must reference Project2", project1.getReferencedProjects(), arrayContaining(project2)); - assertThat("Project2 must not have referenced projects", project2.getReferencedProjects(), emptyArray()); + assertThat(project0.getReferencedProjects()).as("referenced projects of Project0").containsExactly(project1); + assertThat(project1.getReferencedProjects()).as("referenced projects of Project1").containsExactly(project2); + assertThat(project2.getReferencedProjects()).as("referenced projects of Project2").isEmpty(); clearCache(); - assertThat("Project0 must reference Project1 and Project2", project0.getReferencedProjects(), - arrayContaining(project1, project2)); - assertThat("Project1 must reference Project2", project1.getReferencedProjects(), arrayContaining(project2)); - assertThat("Project2 must not have referenced projects", project2.getReferencedProjects(), emptyArray()); + assertThat(project0.getReferencedProjects()).as("referenced projects of Project0").containsExactly(project1, + project2); + assertThat(project1.getReferencedProjects()).as("referenced projects of Project1").containsExactly(project2); + assertThat(project2.getReferencedProjects()).as("referenced projects of Project2").isEmpty(); } @Test public void testReferencedBuildConfigs() throws CoreException { - assertThat("Project0 must not have referenced projects", - project0.getReferencedBuildConfigs(IBuildConfiguration.DEFAULT_CONFIG_NAME, false), emptyArray()); - assertThat("Project1 must not have referenced projects", - project1.getReferencedBuildConfigs(IBuildConfiguration.DEFAULT_CONFIG_NAME, false), emptyArray()); - assertThat("Project2 must not have referenced projects", - project2.getReferencedBuildConfigs(IBuildConfiguration.DEFAULT_CONFIG_NAME, false), emptyArray()); + assertThat(project0.getReferencedBuildConfigs(IBuildConfiguration.DEFAULT_CONFIG_NAME, false)) + .as("referenced build configs of Project0").isEmpty(); + assertThat(project1.getReferencedBuildConfigs(IBuildConfiguration.DEFAULT_CONFIG_NAME, false)) + .as("referenced build configs of Project1").isEmpty(); + assertThat(project2.getReferencedBuildConfigs(IBuildConfiguration.DEFAULT_CONFIG_NAME, false)) + .as("referenced build configs of Project2").isEmpty(); DynamicReferenceProvider.addReference(project0, project1); DynamicReferenceProvider.addReference(project1, project2); @@ -134,65 +131,58 @@ public void testReferencedBuildConfigs() throws CoreException { IBuildConfiguration buildConfigProject1 = project1.getBuildConfig(IBuildConfiguration.DEFAULT_CONFIG_NAME); IBuildConfiguration buildConfigProject2 = project2.getBuildConfig(IBuildConfiguration.DEFAULT_CONFIG_NAME); - assertThat("Build configuration of Project0 must reference build configuration of project1 and project2", - project0.getReferencedBuildConfigs(IBuildConfiguration.DEFAULT_CONFIG_NAME, false), - arrayContaining(buildConfigProject1, buildConfigProject2)); - assertThat("Build configuration of Project1 must reference build configuration of Project2", - project1.getReferencedBuildConfigs(IBuildConfiguration.DEFAULT_CONFIG_NAME, false), - arrayContaining(buildConfigProject2)); - assertThat("Project2 must not have referenced projects", - project2.getReferencedBuildConfigs(IBuildConfiguration.DEFAULT_CONFIG_NAME, false), emptyArray()); + assertThat(project0.getReferencedBuildConfigs(IBuildConfiguration.DEFAULT_CONFIG_NAME, false)) + .as("referenced build configs of Project0") + .containsExactly(buildConfigProject1, buildConfigProject2); + assertThat(project1.getReferencedBuildConfigs(IBuildConfiguration.DEFAULT_CONFIG_NAME, false)) + .as("referenced build configs of Project1") + .containsExactly(buildConfigProject2); + assertThat(project2.getReferencedBuildConfigs(IBuildConfiguration.DEFAULT_CONFIG_NAME, false)) + .as("referenced build configs of Project2").isEmpty(); } @Test public void testReferencingProjects() throws CoreException { - assertThat("Project0 must not have referencing projects", project0.getReferencingProjects(), emptyArray()); - assertThat("Project1 must not have referencing projects", project1.getReferencingProjects(), emptyArray()); - assertThat("Project2 must not have referencing projects", project2.getReferencingProjects(), emptyArray()); + assertThat(project0.getReferencingProjects()).as("referencing projects of Project0").isEmpty(); + assertThat(project1.getReferencingProjects()).as("referencing projects of Project1").isEmpty(); + assertThat(project2.getReferencingProjects()).as("referencing projects of Project2").isEmpty(); DynamicReferenceProvider.addReference(project0, project1); - assertThat("Project0 must not have referencing projects", project0.getReferencingProjects(), emptyArray()); - assertThat("Project1 must not have referencing projects", project1.getReferencingProjects(), emptyArray()); - assertThat("Project2 must not have referencing projects", project2.getReferencingProjects(), emptyArray()); + assertThat(project0.getReferencingProjects()).as("referencing projects of Project0").isEmpty(); + assertThat(project1.getReferencingProjects()).as("referencing projects of Project1").isEmpty(); + assertThat(project2.getReferencingProjects()).as("referencing projects of Project2").isEmpty(); clearCache(); - assertThat("Project0 must not have referencing projects", project0.getReferencingProjects(), emptyArray()); - assertThat("Project1 must be referenced by Project0", project1.getReferencingProjects(), - arrayContaining(project0)); - assertThat("Project2 must not have referencing projects", project2.getReferencingProjects(), emptyArray()); + assertThat(project0.getReferencingProjects()).as("referencing projects of Project0").isEmpty(); + assertThat(project1.getReferencingProjects()).as("referencing projects of Project1").containsExactly(project0); + assertThat(project2.getReferencingProjects()).as("referencing projects of Project2").isEmpty(); DynamicReferenceProvider.addReference(project1, project2); - assertThat("Project0 must not have referencing projects", project0.getReferencingProjects(), emptyArray()); - assertThat("Project1 must must be referenced by Project0", project1.getReferencingProjects(), - arrayContaining(project0)); - assertThat("Project2 must not have referencing projects", project2.getReferencingProjects(), emptyArray()); + assertThat(project0.getReferencingProjects()).as("referencing projects of Project0").isEmpty(); + assertThat(project1.getReferencingProjects()).as("referencing projects of Project1").containsExactly(project0); + assertThat(project2.getReferencingProjects()).as("referencing projects of Project2").isEmpty(); clearCache(); - assertThat("Project0 must not have referencing projects", project0.getReferencingProjects(), emptyArray()); - assertThat("Project1 must be referenced by Project0", project1.getReferencingProjects(), - arrayContaining(project0)); - assertThat("Project2 must be referenced by Project1", project2.getReferencingProjects(), - arrayContaining(project1)); + assertThat(project0.getReferencingProjects()).as("referencing projects of Project0").isEmpty(); + assertThat(project1.getReferencingProjects()).as("referencing projects of Project2").containsExactly(project0); + assertThat(project2.getReferencingProjects()).as("referencing projects of Project2").containsExactly(project1); DynamicReferenceProvider.addReference(project0, project2); - assertThat("Project0 must not have referencing projects", project0.getReferencingProjects(), emptyArray()); - assertThat("Project1 must be referenced by Project0", project1.getReferencingProjects(), - arrayContaining(project0)); - assertThat("Project2 must be referenced by Project1", project2.getReferencingProjects(), - arrayContaining(project1)); + assertThat(project0.getReferencingProjects()).as("referencing projects of Project0").isEmpty(); + assertThat(project1.getReferencingProjects()).as("referencing projects of Project1").containsExactly(project0); + assertThat(project2.getReferencingProjects()).as("referencing projects of Project2").containsExactly(project1); clearCache(); - assertThat("Project0 must not have referencing projects", project0.getReferencingProjects(), emptyArray()); - assertThat("Project1 must be referenced by Project0", project1.getReferencingProjects(), - arrayContaining(project0)); - assertThat("Project2 must be referenced by Project0 and Project1", project2.getReferencingProjects(), - arrayContaining(project0, project1)); + assertThat(project0.getReferencingProjects()).as("referencing projects of Project0").isEmpty(); + assertThat(project1.getReferencingProjects()).as("referencing projects of Project1").containsExactly(project0); + assertThat(project2.getReferencingProjects()).as("referencing projects of Project2").containsExactly(project0, + project1); } @Test @@ -201,9 +191,9 @@ public void testComputeProjectOrder() throws CoreException { ProjectOrder projectOrder = getWorkspace().computeProjectOrder(allProjects); - assertThat("Build order not defined, must return projects in default order", projectOrder.projects, - is(allProjects)); - assertThat("Project order should not have cycles: " + projectOrder, !projectOrder.hasCycles); + // Build order not defined, must return projects in default order + assertThat(projectOrder.projects).as("build order").isEqualTo(allProjects); + assertThat(projectOrder.hasCycles).withFailMessage("build order has cycles: %s", projectOrder).isFalse(); DynamicReferenceProvider.addReference(project0, project1); DynamicReferenceProvider.addReference(project1, project2); @@ -211,9 +201,8 @@ public void testComputeProjectOrder() throws CoreException { projectOrder = getWorkspace().computeProjectOrder(allProjects); - assertThat("Build order must be Project2, Project1, Project0", projectOrder.projects, - arrayContaining(project2, project1, project0)); - assertThat("Project order should not have cycles: " + projectOrder, !projectOrder.hasCycles); + assertThat(projectOrder.projects).as("build order").containsExactly(project2, project1, project0); + assertThat(projectOrder.hasCycles).withFailMessage("build order has cycless: %s", projectOrder).isFalse(); DynamicReferenceProvider.clear(); DynamicReferenceProvider.addReference(project1, project0); @@ -222,9 +211,8 @@ public void testComputeProjectOrder() throws CoreException { projectOrder = getWorkspace().computeProjectOrder(allProjects); - assertThat("Build order must be Project2, Project0, Project1", - projectOrder.projects, arrayContaining(project2, project0, project1)); - assertThat("Project order should not have cycles: " + projectOrder, !projectOrder.hasCycles); + assertThat(projectOrder.projects).as("build order").containsExactly(project2, project0, project1); + assertThat(projectOrder.hasCycles).withFailMessage("build order has cycles: %s", projectOrder).isFalse(); } @Test @@ -237,14 +225,13 @@ public void testBug543776() throws Exception { project0.create(null); project0.open(null); - assertThat(project0.getName(), is(PROJECT_0_NAME)); - assertThat(project0.getDescription().getName(), is("anotherName")); + assertThat(project0.getName()).isEqualTo(PROJECT_0_NAME); + assertThat(project0.getDescription().getName()).isEqualTo("anotherName"); DynamicReferenceProvider.addReference(project0, project1); clearCache(); - assertThat("Project0 must reference Project1", project0.getReferencedProjects(), - arrayContaining(project1)); + assertThat(project0.getReferencedProjects()).as("referenced projects of Project0").containsExactly(project1); } private void clearCache() { diff --git a/resources/tests/org.eclipse.core.tests.resources/src/org/eclipse/core/tests/internal/resources/ProjectPreferencesTest.java b/resources/tests/org.eclipse.core.tests.resources/src/org/eclipse/core/tests/internal/resources/ProjectPreferencesTest.java index c313cf14879..1557bce3e9f 100644 --- a/resources/tests/org.eclipse.core.tests.resources/src/org/eclipse/core/tests/internal/resources/ProjectPreferencesTest.java +++ b/resources/tests/org.eclipse.core.tests.resources/src/org/eclipse/core/tests/internal/resources/ProjectPreferencesTest.java @@ -14,6 +14,7 @@ *******************************************************************************/ package org.eclipse.core.tests.internal.resources; +import static org.assertj.core.api.Assertions.assertThat; import static org.eclipse.core.resources.ResourcesPlugin.getWorkspace; import static org.eclipse.core.tests.resources.ResourceTestUtil.createInWorkspace; import static org.eclipse.core.tests.resources.ResourceTestUtil.createTestMonitor; @@ -22,9 +23,6 @@ import static org.eclipse.core.tests.resources.ResourceTestUtil.removeFromWorkspace; import static org.eclipse.core.tests.resources.ResourceTestUtil.touchInFilesystem; import static org.eclipse.core.tests.resources.ResourceTestUtil.waitForBuild; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.not; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; @@ -526,7 +524,7 @@ public void test_61843() throws Exception { if (exception == null || !(exception instanceof CoreException coreException)) { return; } - assertThat(IResourceStatus.WORKSPACE_LOCKED, not(is(coreException.getStatus().getCode()))); + assertThat(IResourceStatus.WORKSPACE_LOCKED).isNotEqualTo(coreException.getStatus().getCode()); }; // listener to react to changes in the workspace diff --git a/resources/tests/org.eclipse.core.tests.resources/src/org/eclipse/core/tests/internal/resources/ProjectReferencesTest.java b/resources/tests/org.eclipse.core.tests.resources/src/org/eclipse/core/tests/internal/resources/ProjectReferencesTest.java index 06a11bf0007..dd60a92da5f 100644 --- a/resources/tests/org.eclipse.core.tests.resources/src/org/eclipse/core/tests/internal/resources/ProjectReferencesTest.java +++ b/resources/tests/org.eclipse.core.tests.resources/src/org/eclipse/core/tests/internal/resources/ProjectReferencesTest.java @@ -13,13 +13,10 @@ *******************************************************************************/ package org.eclipse.core.tests.internal.resources; +import static org.assertj.core.api.Assertions.assertThat; import static org.eclipse.core.resources.ResourcesPlugin.getWorkspace; import static org.eclipse.core.tests.resources.ResourceTestUtil.createInWorkspace; import static org.eclipse.core.tests.resources.ResourceTestUtil.createTestMonitor; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.arrayContaining; -import static org.hamcrest.Matchers.emptyArray; -import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThrows; import org.eclipse.core.internal.resources.BuildConfiguration; @@ -95,16 +92,16 @@ private void setUpVariants(IProject project) throws CoreException { public void testAddReferencesToNonExistantConfigs() throws CoreException { IProjectDescription desc = project0.getDescription(); - assertThat("project '" + project0 + "' has unexpected build config: " + nonExistentBC, - !project0.hasBuildConfig(nonExistentBC)); + assertThat(project0.hasBuildConfig(nonExistentBC)) + .withFailMessage("project '%s' has unexpected build config: %s", project0, nonExistentBC).isFalse(); desc.setBuildConfigReferences(nonExistentBC, new IBuildConfiguration[] {project1v0}); project0.setDescription(desc, createTestMonitor()); - assertThat("project '" + project0 + "' has unexpected build config: " + nonExistentBC, - !project0.hasBuildConfig(nonExistentBC)); + assertThat(project0.hasBuildConfig(nonExistentBC)) + .withFailMessage("project '%s' has unexpected build config: %s", project0, nonExistentBC).isFalse(); - assertThat(desc.getBuildConfigReferences(nonExistentBC), emptyArray()); + assertThat(desc.getBuildConfigReferences(nonExistentBC)).isEmpty(); assertThrows(CoreException.class, () -> project0.getReferencedBuildConfigs(nonExistentBC, true)); } @@ -127,29 +124,29 @@ public void testChangingBuildConfigurations() throws CoreException { // Check build configa desc = project0.getDescription(); - assertThat(desc.getBuildConfigReferences(project0v0.getName()), is(refs)); - assertThat(desc.getBuildConfigReferences(project0v1.getName()), is(refs2)); + assertThat(desc.getBuildConfigReferences(project0v0.getName())).isEqualTo(refs); + assertThat(desc.getBuildConfigReferences(project0v1.getName())).isEqualTo(refs2); // Resetting the build configs doesn't change anything desc.setBuildConfigs(new String[] {project0v0.getName(), project0v1.getName()}); project0.setDescription(desc, createTestMonitor()); desc = project0.getDescription(); - assertThat(desc.getBuildConfigReferences(project0v0.getName()), is(refs)); - assertThat(desc.getBuildConfigReferences(project0v1.getName()), is(refs2)); + assertThat(desc.getBuildConfigReferences(project0v0.getName())).isEqualTo(refs); + assertThat(desc.getBuildConfigReferences(project0v1.getName())).isEqualTo(refs2); // Removing a build configuration removes the references desc.setBuildConfigs(new String[] {project0v0.getName()}); project0.setDescription(desc, createTestMonitor()); desc = project0.getDescription(); - assertThat(desc.getBuildConfigReferences(project0v0.getName()), is(refs)); - assertThat(desc.getBuildConfigReferences(project0v1.getName()), emptyArray()); + assertThat(desc.getBuildConfigReferences(project0v0.getName())).isEqualTo(refs); + assertThat(desc.getBuildConfigReferences(project0v1.getName())).isEmpty(); // Re-adding a build configuration doesn't make references re-appear desc.setBuildConfigs(new String[] {project0v0.getName()}); project0.setDescription(desc, createTestMonitor()); desc = project0.getDescription(); - assertThat(desc.getBuildConfigReferences(project0v0.getName()), is(refs)); - assertThat(desc.getBuildConfigReferences(project0v1.getName()), emptyArray()); + assertThat(desc.getBuildConfigReferences(project0v0.getName())).isEqualTo(refs); + assertThat(desc.getBuildConfigReferences(project0v1.getName())).isEmpty(); } /** @@ -165,13 +162,13 @@ public void testMixedProjectAndBuildConfigRefs() throws CoreException { // Check getters desc = project0.getDescription(); - assertThat(desc.getDynamicReferences(), arrayContaining(project1, project3)); - assertThat(desc.getBuildConfigReferences(project0v0.getName()), emptyArray()); - assertThat(desc.getBuildConfigReferences(project0v1.getName()), emptyArray()); - assertThat(project0.getReferencedBuildConfigs(project0v0.getName(), false), - arrayContaining(project1.getActiveBuildConfig(), project3.getActiveBuildConfig())); - assertThat(project0.getReferencedBuildConfigs(project0v1.getName(), false), - arrayContaining(project1.getActiveBuildConfig(), project3.getActiveBuildConfig())); + assertThat(desc.getDynamicReferences()).containsExactly(project1, project3); + assertThat(desc.getBuildConfigReferences(project0v0.getName())).isEmpty(); + assertThat(desc.getBuildConfigReferences(project0v1.getName())).isEmpty(); + assertThat(project0.getReferencedBuildConfigs(project0v0.getName(), false)) + .containsExactly(project1.getActiveBuildConfig(), project3.getActiveBuildConfig()); + assertThat(project0.getReferencedBuildConfigs(project0v1.getName(), false)) + .containsExactly(project1.getActiveBuildConfig(), project3.getActiveBuildConfig()); // Now set dynamic references on config1 desc.setBuildConfigReferences(project0v0.getName(), new IBuildConfiguration[] {project3v1, project2v0, project1v0}); @@ -180,14 +177,14 @@ public void testMixedProjectAndBuildConfigRefs() throws CoreException { // Check references // This is deterministic as config0 is listed first, so we expect its config order to trump cofig1's desc = project0.getDescription(); - assertThat(desc.getDynamicReferences(), arrayContaining(project1, project3)); - assertThat(desc.getBuildConfigReferences(project0v0.getName()), - arrayContaining(project3v1, project2v0, project1v0)); + assertThat(desc.getDynamicReferences()).containsExactly(project1, project3); + assertThat(desc.getBuildConfigReferences(project0v0.getName())).containsExactly(project3v1, project2v0, + project1v0); // Now at the project leve - assertThat(project0.getReferencedBuildConfigs(project0v0.getName(), false), - arrayContaining(project3v1, project2v0, project1v0, project3v0)); - assertThat(project0.getReferencedBuildConfigs(project0v1.getName(), false), - arrayContaining(project1.getActiveBuildConfig(), project3.getActiveBuildConfig())); + assertThat(project0.getReferencedBuildConfigs(project0v0.getName(), false)).containsExactly(project3v1, + project2v0, project1v0, project3v0); + assertThat(project0.getReferencedBuildConfigs(project0v1.getName(), false)) + .containsExactly(project1.getActiveBuildConfig(), project3.getActiveBuildConfig()); } @Test @@ -215,14 +212,14 @@ public void testSetAndGetProjectReferences() throws CoreException { // Test getters desc = project0.getDescription(); - assertThat(desc.getReferencedProjects(), arrayContaining(project3, project1)); - assertThat(desc.getDynamicReferences(), arrayContaining(project1, project2)); - assertThat(desc.getBuildConfigReferences(bc0), emptyArray()); - - assertThat(project0.getReferencedProjects(), arrayContaining(project3, project1, project2)); - assertThat(project0.getReferencingProjects(), arrayContaining(project1, project3)); - assertThat(project0.getReferencedBuildConfigs(project0v0.getName(), true), - arrayContaining(project3v0, project1v0, project2v0)); + assertThat(desc.getReferencedProjects()).containsExactly(project3, project1); + assertThat(desc.getDynamicReferences()).containsExactly(project1, project2); + assertThat(desc.getBuildConfigReferences(bc0)).isEmpty(); + + assertThat(project0.getReferencedProjects()).containsExactly(project3, project1, project2); + assertThat(project0.getReferencingProjects()).containsExactly(project1, project3); + assertThat(project0.getReferencedBuildConfigs(project0v0.getName(), true)).containsExactly(project3v0, + project1v0, project2v0); } @Test @@ -251,17 +248,17 @@ public void testSetAndGetProjectConfigReferences() throws CoreException { // Check getters desc = project0.getDescription(); - assertThat(desc.getReferencedProjects(), arrayContaining(project1)); - assertThat(desc.getDynamicReferences(), arrayContaining(project3)); - assertThat(desc.getBuildConfigReferences(bc0), arrayContaining(project2v0, project1v0)); - assertThat(desc.getBuildConfigReferences(bc1), arrayContaining(project2v0)); - - assertThat(project0.getReferencedProjects(), arrayContaining(project2, project1, project3)); - assertThat(project0.getReferencingProjects(), arrayContaining(project1, project3)); - assertThat(project0.getReferencedBuildConfigs(project0v0.getName(), true), - arrayContaining(project2v0, project1v0, project3.getActiveBuildConfig())); - assertThat(project0.getReferencedBuildConfigs(project0v1.getName(), true), arrayContaining( - project2v0, project1.getActiveBuildConfig(), project3.getActiveBuildConfig())); + assertThat(desc.getReferencedProjects()).containsExactly(project1); + assertThat(desc.getDynamicReferences()).containsExactly(project3); + assertThat(desc.getBuildConfigReferences(bc0)).containsExactly(project2v0, project1v0); + assertThat(desc.getBuildConfigReferences(bc1)).containsExactly(project2v0); + + assertThat(project0.getReferencedProjects()).containsExactly(project2, project1, project3); + assertThat(project0.getReferencingProjects()).containsExactly(project1, project3); + assertThat(project0.getReferencedBuildConfigs(project0v0.getName(), true)).containsExactly(project2v0, + project1v0, project3.getActiveBuildConfig()); + assertThat(project0.getReferencedBuildConfigs(project0v1.getName(), true)).containsExactly(project2v0, + project1.getActiveBuildConfig(), project3.getActiveBuildConfig()); } @Test @@ -270,9 +267,8 @@ public void testReferencesToActiveConfigs() throws CoreException { desc.setBuildConfigReferences(bc0, new IBuildConfiguration[] {getRef(project1)}); project0.setDescription(desc, createTestMonitor()); - assertThat(desc.getBuildConfigReferences(bc0), arrayContaining(getRef(project1))); - assertThat(project0.getReferencedBuildConfigs(project0v0.getName(), true), - arrayContaining(project1v0)); + assertThat(desc.getBuildConfigReferences(bc0)).containsExactly(getRef(project1)); + assertThat(project0.getReferencedBuildConfigs(project0v0.getName(), true)).containsExactly(project1v0); } } diff --git a/resources/tests/org.eclipse.core.tests.resources/src/org/eclipse/core/tests/internal/resources/WorkspacePreferencesTest.java b/resources/tests/org.eclipse.core.tests.resources/src/org/eclipse/core/tests/internal/resources/WorkspacePreferencesTest.java index c6b3b12524b..d771fd3f8ec 100644 --- a/resources/tests/org.eclipse.core.tests.resources/src/org/eclipse/core/tests/internal/resources/WorkspacePreferencesTest.java +++ b/resources/tests/org.eclipse.core.tests.resources/src/org/eclipse/core/tests/internal/resources/WorkspacePreferencesTest.java @@ -14,12 +14,11 @@ *******************************************************************************/ package org.eclipse.core.tests.internal.resources; +import static org.assertj.core.api.Assertions.assertThat; import static org.eclipse.core.tests.harness.FileSystemHelper.getRandomLocation; import static org.eclipse.core.tests.resources.ResourceTestPluginConstants.PI_RESOURCES_TESTS; import static org.eclipse.core.tests.resources.ResourceTestUtil.createRandomString; import static org.eclipse.core.tests.resources.ResourceTestUtil.removeFromFileSystem; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.is; import java.util.Arrays; import java.util.LinkedList; @@ -273,7 +272,7 @@ public void assertEquals(String message, IWorkspaceDescription description, Pref */ public void assertEquals(String message, IWorkspaceDescription description1, IWorkspaceDescription description2) throws ComparisonFailure { assertEquals(message + " - 1", description1.isAutoBuilding(), description2.isAutoBuilding()); - assertThat(message + " - 2", description1.getBuildOrder(), is(description2.getBuildOrder())); + assertThat(description1.getBuildOrder()).as(message + " - 2").isEqualTo(description2.getBuildOrder()); assertEquals(message + " - 3", WorkspacePreferences.convertStringArraytoString(description1.getBuildOrder()), WorkspacePreferences.convertStringArraytoString(description2.getBuildOrder())); assertEquals(message + " - 4", description1.isApplyFileStatePolicy(), description2.isApplyFileStatePolicy()); assertEquals(message + " - 5", description1.getFileStateLongevity(), description2.getFileStateLongevity()); diff --git a/resources/tests/org.eclipse.core.tests.resources/src/org/eclipse/core/tests/resources/IResourceChangeListenerTest.java b/resources/tests/org.eclipse.core.tests.resources/src/org/eclipse/core/tests/resources/IResourceChangeListenerTest.java index 4b693bded41..f5f603156b8 100644 --- a/resources/tests/org.eclipse.core.tests.resources/src/org/eclipse/core/tests/resources/IResourceChangeListenerTest.java +++ b/resources/tests/org.eclipse.core.tests.resources/src/org/eclipse/core/tests/resources/IResourceChangeListenerTest.java @@ -14,6 +14,7 @@ ******************************************************************************/ package org.eclipse.core.tests.resources; +import static org.assertj.core.api.Assertions.assertThat; import static org.eclipse.core.resources.ResourcesPlugin.getWorkspace; import static org.eclipse.core.tests.harness.FileSystemHelper.getRandomLocation; import static org.eclipse.core.tests.harness.FileSystemHelper.getTempDir; @@ -27,7 +28,6 @@ import static org.eclipse.core.tests.resources.ResourceTestUtil.setAutoBuilding; import static org.eclipse.core.tests.resources.ResourceTestUtil.waitForBuild; import static org.eclipse.core.tests.resources.ResourceTestUtil.waitForRefresh; -import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; @@ -895,13 +895,14 @@ public void resourceChanged(IResourceChangeEvent event) { Job.getJobManager().wakeUp(ResourcesPlugin.FAMILY_MANUAL_REFRESH); Job.getJobManager().join(ResourcesPlugin.FAMILY_MANUAL_REFRESH, null); - assertThat("Refreshing resource in first resource change listener did not succeed", - listener1.refreshPerformed); + assertThat(listener1.refreshPerformed) + .withFailMessage("Refreshing resource in first resource change listener did not succeed").isTrue(); if (listener1.exception != null) { throw listener1.exception; } - assertThat("Refreshing resource in second resource change listener unexpectedly succeeded", - !listener2.refreshSucceeded); + assertThat(listener2.refreshSucceeded) + .withFailMessage("Refreshing resource in second resource change listener unexpectedly succeeded") + .isFalse(); } finally { getWorkspace().removeResourceChangeListener(listener1); diff --git a/resources/tests/org.eclipse.core.tests.resources/src/org/eclipse/core/tests/resources/IResourceTest.java b/resources/tests/org.eclipse.core.tests.resources/src/org/eclipse/core/tests/resources/IResourceTest.java index e3ec73ffbb3..0d6ebdd2e78 100644 --- a/resources/tests/org.eclipse.core.tests.resources/src/org/eclipse/core/tests/resources/IResourceTest.java +++ b/resources/tests/org.eclipse.core.tests.resources/src/org/eclipse/core/tests/resources/IResourceTest.java @@ -15,6 +15,7 @@ package org.eclipse.core.tests.resources; import static java.io.InputStream.nullInputStream; +import static org.assertj.core.api.Assertions.assertThat; import static org.eclipse.core.resources.ResourcesPlugin.getWorkspace; import static org.eclipse.core.tests.harness.FileSystemHelper.getRandomLocation; import static org.eclipse.core.tests.resources.ResourceTestUtil.assertDoesNotExistInFileSystem; @@ -34,9 +35,6 @@ import static org.eclipse.core.tests.resources.ResourceTestUtil.setAutoBuilding; import static org.eclipse.core.tests.resources.ResourceTestUtil.touchInFilesystem; import static org.eclipse.core.tests.resources.ResourceTestUtil.waitForBuild; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.empty; -import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotEquals; @@ -2593,7 +2591,7 @@ public void logging(IStatus status, String plugin) { } void assertNoLoggedErrors() { - assertThat(errors, is(empty())); + assertThat(errors).isEmpty(); } } diff --git a/resources/tests/org.eclipse.core.tests.resources/src/org/eclipse/core/tests/resources/ISynchronizerTest.java b/resources/tests/org.eclipse.core.tests.resources/src/org/eclipse/core/tests/resources/ISynchronizerTest.java index 1643f07a5c7..cf3d7eec67c 100644 --- a/resources/tests/org.eclipse.core.tests.resources/src/org/eclipse/core/tests/resources/ISynchronizerTest.java +++ b/resources/tests/org.eclipse.core.tests.resources/src/org/eclipse/core/tests/resources/ISynchronizerTest.java @@ -14,6 +14,7 @@ *******************************************************************************/ package org.eclipse.core.tests.resources; +import static org.assertj.core.api.Assertions.assertThat; import static org.eclipse.core.resources.ResourcesPlugin.getWorkspace; import static org.eclipse.core.tests.resources.ResourceTestPluginConstants.PI_RESOURCES_TESTS; import static org.eclipse.core.tests.resources.ResourceTestUtil.buildResources; @@ -21,11 +22,6 @@ import static org.eclipse.core.tests.resources.ResourceTestUtil.createRandomString; import static org.eclipse.core.tests.resources.ResourceTestUtil.createTestMonitor; import static org.eclipse.core.tests.resources.ResourceTestUtil.removeFromWorkspace; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.arrayWithSize; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.notNullValue; -import static org.hamcrest.Matchers.nullValue; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertThrows; @@ -117,14 +113,11 @@ public void tearDown() throws Exception { private void assertExpectedSyncInfo(IResource resource, byte[] actualSyncInfo, byte[] expectedSyncInfo) { if (resource.getType() == IResource.ROOT) { - assertThat("Sync info for root resource should be null: " + resource.getFullPath(), actualSyncInfo, - nullValue()); + assertThat(actualSyncInfo).as("sync info for root resource: %s", resource.getFullPath()).isNull(); return; } - assertThat("Sync info for non-root resource should not be null: " + resource.getFullPath(), actualSyncInfo, - notNullValue()); - assertThat("Unexpected sync info for resource: " + resource.getFullPath(), expectedSyncInfo, - is(actualSyncInfo)); + assertThat(actualSyncInfo).as("sync info for non-root resource: %s", resource.getFullPath()).isNotNull() + .isEqualTo(expectedSyncInfo); } @Test @@ -295,10 +288,9 @@ public void testMoveResource() throws CoreException { // check sync info byte[] syncInfo = synchronizer.getSyncInfo(qname, source); - assertThat("sync info at source should not be null: " + source.getFullPath(), syncInfo, notNullValue()); - assertThat("unexpected sync info for resource: " + source.getFullPath(), syncInfo, is(b)); - assertThat("sync info at destination should be null: " + destination.getFullPath(), - synchronizer.getSyncInfo(qname, destination), nullValue()); + assertThat(syncInfo).as("sync info at source: %s", source.getFullPath()).isNotNull().isEqualTo(b); + assertThat(synchronizer.getSyncInfo(qname, destination)) + .as("sync info at destination: %s", destination.getFullPath()).isNull(); } @Test @@ -328,20 +320,19 @@ public void testMoveResource2() throws CoreException { // check sync info byte[] syncInfo = synchronizer.getSyncInfo(qname, sourceFile); - assertThat("sync info at source should not be null: " + sourceFile.getFullPath(), syncInfo, notNullValue()); - assertThat("unexpected sync info for resource: " + sourceFile.getFullPath(), syncInfo, is(b)); - assertThat("sync info at destination should be null: " + destFile.getFullPath(), - synchronizer.getSyncInfo(qname, destFile), nullValue()); + assertThat(syncInfo).as("sync info at source: %s", sourceFile.getFullPath()).isNotNull().isNotNull() + .isEqualTo(b); + assertThat(synchronizer.getSyncInfo(qname, destFile)).as("sync info at destination: %s", destFile.getFullPath()) + .isNull(); // move the file back destFile.move(sourceFile.getFullPath(), true, createTestMonitor()); // check the sync info syncInfo = synchronizer.getSyncInfo(qname, sourceFile); - assertThat("sync info at source should not be null: " + sourceFile.getFullPath(), syncInfo, notNullValue()); - assertThat("unexpected sync info for resource: " + sourceFile.getFullPath(), syncInfo, is(b)); - assertThat("sync info at destination should be null: " + destFile.getFullPath(), - synchronizer.getSyncInfo(qname, destFile), nullValue()); + assertThat(syncInfo).as("sync info at source: %s", sourceFile.getFullPath()).isEqualTo(b); + assertThat(synchronizer.getSyncInfo(qname, destFile)) + .as("sync info at destination: %s", destFile.getFullPath()).isNull(); // rename the file and ensure that the sync info is moved with it IProject destProject = getWorkspace().getRoot().getProject("newProject"); @@ -349,11 +340,9 @@ public void testMoveResource2() throws CoreException { assertNull("7.1", synchronizer.getSyncInfo(qname, sourceProject)); assertNull("7.2", synchronizer.getSyncInfo(qname, sourceFile)); syncInfo = synchronizer.getSyncInfo(qname, destProject.getFile(sourceFile.getName())); - assertThat("sync info should not be null: " + sourceFile.getFullPath(), syncInfo, notNullValue()); - assertThat("unexpected sync info for resource: " + sourceFile.getFullPath(), syncInfo, is(b)); + assertThat(syncInfo).as("sync info for resource: %s", sourceFile.getFullPath()).isNotNull().isEqualTo(b); syncInfo = synchronizer.getSyncInfo(qname, destProject); - assertThat("sync info should not be null: " + sourceFile.getFullPath(), syncInfo, notNullValue()); - assertThat("unexpected sync info for resource: " + sourceFile.getFullPath(), syncInfo, is(b)); + assertThat(syncInfo).as("sync info for resource: %s", sourceFile.getFullPath()).isNotNull().isEqualTo(b); } @Test @@ -374,13 +363,13 @@ public void testRegistration() { // get the array of targets QualifiedName[] list = synchronizer.getPartners(); - assertThat(list, arrayWithSize(NUMBER_OF_PARTNERS)); + assertThat(list).hasSize(NUMBER_OF_PARTNERS); // unregister all targets for (int i = 0; i < NUMBER_OF_PARTNERS; i++) { synchronizer.remove(partners[i]); } - assertThat(synchronizer.getPartners(), arrayWithSize(0)); + assertThat(synchronizer.getPartners()).isEmpty(); } @Test diff --git a/resources/tests/org.eclipse.core.tests.resources/src/org/eclipse/core/tests/resources/MarkerTest.java b/resources/tests/org.eclipse.core.tests.resources/src/org/eclipse/core/tests/resources/MarkerTest.java index c60155c65f4..aae99c8986e 100644 --- a/resources/tests/org.eclipse.core.tests.resources/src/org/eclipse/core/tests/resources/MarkerTest.java +++ b/resources/tests/org.eclipse.core.tests.resources/src/org/eclipse/core/tests/resources/MarkerTest.java @@ -14,6 +14,7 @@ *******************************************************************************/ package org.eclipse.core.tests.resources; +import static org.assertj.core.api.Assertions.assertThat; import static org.eclipse.core.resources.ResourcesPlugin.getWorkspace; import static org.eclipse.core.tests.resources.ResourceTestUtil.buildResources; import static org.eclipse.core.tests.resources.ResourceTestUtil.createInWorkspace; @@ -22,12 +23,6 @@ import static org.eclipse.core.tests.resources.ResourceTestUtil.createTestMonitor; import static org.eclipse.core.tests.resources.ResourceTestUtil.createUniqueString; import static org.eclipse.core.tests.resources.ResourceTestUtil.waitForEncodingRelatedJobs; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.arrayContainingInAnyOrder; -import static org.hamcrest.Matchers.arrayWithSize; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.not; -import static org.hamcrest.Matchers.nullValue; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertThrows; import static org.junit.Assert.assertTrue; @@ -48,6 +43,7 @@ import java.util.Map; import java.util.Vector; import java.util.concurrent.atomic.AtomicReference; +import org.assertj.core.api.ObjectAssert; import org.eclipse.core.internal.resources.MarkerManager; import org.eclipse.core.internal.resources.MarkerReader; import org.eclipse.core.internal.resources.Resource; @@ -149,13 +145,19 @@ protected void assertMarkerExists(IMarker marker) { private void assertMarkerHasAttributeValue(IMarker marker, String attributeName, Object expectedValue) throws CoreException { - assertThat("marker has unexpected attribute value: " + marker, marker.getAttribute(attributeName), - expectedValue == null ? is(nullValue()) : is(expectedValue)); + ObjectAssert asserted = assertThat(marker.getAttribute(attributeName)) + .as("attribute %s of marker %s", attributeName, marker); + if (expectedValue == null) { + asserted.isNull(); + } else { + asserted.isEqualTo(expectedValue); + } + } private void assertSingleMarkerWithId(IMarker[] markers, long id) { - assertThat(markers, arrayWithSize(1)); - assertThat("wrong id in marker " + markers[0], markers[0].getId(), is(id)); + assertThat(markers).hasSize(1).satisfiesExactly( + marker -> assertThat(marker.getId()).as("id of marker %s", marker).isEqualTo(id)); } private void assertMarkerIsSubtype(IMarker marker, String superType) throws CoreException { @@ -343,7 +345,7 @@ public void testThatSettingAttributesTriggerAdditionalResourceChangeEvent() thro IMarker marker = resource.createMarker(TEST_PROBLEM_MARKER); marker.setAttribute(IMarker.MESSAGE, createRandomString()); marker.setAttribute(IMarker.PRIORITY, IMarker.PRIORITY_HIGH); - assertThat(listener.numberOfChanges(), is(3)); + assertThat(listener.numberOfChanges()).isEqualTo(3); } } @@ -360,7 +362,7 @@ public void testThatMarkersWithAttributesOnlyTriggerOnResourceChangeEvent() thro // each setAttributes triggers one resource change event resource.createMarker(TEST_PROBLEM_MARKER, Map.of(IMarker.MESSAGE, createRandomString(), IMarker.PRIORITY, IMarker.PRIORITY_HIGH)); - assertThat(listener.numberOfChanges(), is(1)); + assertThat(listener.numberOfChanges()).isEqualTo(1); } } @@ -368,8 +370,8 @@ public void testThatMarkersWithAttributesOnlyTriggerOnResourceChangeEvent() thro public void testCreationTime() throws CoreException { for (IResource element : resources) { IMarker marker = element.createMarker(IMarker.PROBLEM); - assertThat("creation time for marker in resource " + element.getFullPath() + " is not set", - marker.getCreationTime(), not(is(0))); + assertThat(marker.getCreationTime()) + .withFailMessage("creation time for marker in resource %s is not set", element.getFullPath()).isNotZero(); } } @@ -433,12 +435,12 @@ public void testFindMarkers() throws CoreException { // test finding some markers which actually exist IMarker[] markers = createMarkers(resources, IMarker.PROBLEM); IMarker[] found = getWorkspace().getRoot().findMarkers(IMarker.PROBLEM, false, IResource.DEPTH_INFINITE); - assertThat(found, arrayContainingInAnyOrder(markers)); + assertThat(found).containsExactlyInAnyOrder(markers); found = getWorkspace().getRoot().findMarkers(IMarker.PROBLEM, true, IResource.DEPTH_INFINITE); - assertThat(found, arrayContainingInAnyOrder(markers)); + assertThat(found).containsExactlyInAnyOrder(markers); // test finding some markers which don't exist found = getWorkspace().getRoot().findMarkers(IMarker.BOOKMARK, false, IResource.DEPTH_INFINITE); - assertThat(found, arrayWithSize(0)); + assertThat(found).isEmpty(); // add more markers and do a search on all marker types Vector allMarkers = new Vector<>(markers.length * 3); @@ -448,9 +450,9 @@ public void testFindMarkers() throws CoreException { markers = createMarkers(resources, IMarker.TASK); Collections.addAll(allMarkers, markers); found = getWorkspace().getRoot().findMarkers(null, false, IResource.DEPTH_INFINITE); - assertThat(found, arrayContainingInAnyOrder(allMarkers.toArray(new IMarker[allMarkers.size()]))); + assertThat(found).containsExactlyInAnyOrderElementsOf(allMarkers); found = getWorkspace().getRoot().findMarkers(IMarker.MARKER, true, IResource.DEPTH_INFINITE); - assertThat(found, arrayContainingInAnyOrder(allMarkers.toArray(new IMarker[allMarkers.size()]))); + assertThat(found).containsExactlyInAnyOrderElementsOf(allMarkers); } /* @@ -468,7 +470,7 @@ public void test_35300() throws CoreException { marker.setAttribute(IMarker.TRANSIENT, expected); int actual = marker.getAttribute(IMarker.TRANSIENT, -1); - assertThat(actual, is(expected)); + assertThat(actual).isEqualTo(expected); marker.setAttribute(IMarker.MESSAGE, createRandomString()); } @@ -480,9 +482,9 @@ public void test_10989() throws CoreException { file.create(createRandomContentsStream(), true, null); file.createMarker(IMarker.PROBLEM); IMarker[] found = file.findMarkers(IMarker.PROBLEM, true, IResource.DEPTH_ZERO); - assertThat(found, arrayWithSize(1)); + assertThat(found).hasSize(1); found = file.findMarkers(IMarker.PROBLEM, true, IResource.DEPTH_INFINITE); - assertThat(found, arrayWithSize(1)); + assertThat(found).hasSize(1); project.delete(true, true, null); } @@ -518,46 +520,49 @@ public void testFindMaxProblemSeverity() throws CoreException { IResource[] allResources = new IResource[] {project, folder, sub, topFile, subFile}; createInWorkspace(allResources); - assertThat(root.findMaxProblemSeverity(IMarker.PROBLEM, true, IResource.DEPTH_INFINITE), is(-1)); - assertThat(root.findMaxProblemSeverity(IMarker.TASK, true, IResource.DEPTH_INFINITE), is(-1)); - assertThat(root.findMaxProblemSeverity(IMarker.PROBLEM, true, IResource.DEPTH_ZERO), is(-1)); + assertThat(root.findMaxProblemSeverity(IMarker.PROBLEM, true, IResource.DEPTH_INFINITE)).isEqualTo(-1); + assertThat(root.findMaxProblemSeverity(IMarker.TASK, true, IResource.DEPTH_INFINITE)).isEqualTo(-1); + assertThat(root.findMaxProblemSeverity(IMarker.PROBLEM, true, IResource.DEPTH_ZERO)).isEqualTo(-1); createProblem(subFile, IMarker.SEVERITY_INFO); - assertThat(root.findMaxProblemSeverity(IMarker.PROBLEM, true, IResource.DEPTH_INFINITE), - is(IMarker.SEVERITY_INFO)); - assertThat(root.findMaxProblemSeverity(IMarker.PROBLEM, true, IResource.DEPTH_ONE), is(-1)); - assertThat(root.findMaxProblemSeverity(IMarker.PROBLEM, true, IResource.DEPTH_ZERO), is(-1)); - assertThat(root.findMaxProblemSeverity(IMarker.TASK, true, IResource.DEPTH_INFINITE), is(-1)); - - assertThat(folder.findMaxProblemSeverity(IMarker.PROBLEM, true, IResource.DEPTH_INFINITE), - is(IMarker.SEVERITY_INFO)); - assertThat(folder.findMaxProblemSeverity(IMarker.PROBLEM, true, IResource.DEPTH_ONE), is(-1)); - assertThat(folder.findMaxProblemSeverity(IMarker.PROBLEM, true, IResource.DEPTH_ZERO), is(-1)); - assertThat(folder.findMaxProblemSeverity(IMarker.TASK, true, IResource.DEPTH_INFINITE), is(-1)); - - assertThat(sub.findMaxProblemSeverity(IMarker.PROBLEM, true, IResource.DEPTH_INFINITE), - is(IMarker.SEVERITY_INFO)); - assertThat(sub.findMaxProblemSeverity(IMarker.PROBLEM, true, IResource.DEPTH_ONE), is(IMarker.SEVERITY_INFO)); - assertThat(sub.findMaxProblemSeverity(IMarker.PROBLEM, true, IResource.DEPTH_ZERO), is(-1)); - assertThat(sub.findMaxProblemSeverity(IMarker.TASK, true, IResource.DEPTH_INFINITE), is(-1)); - - assertThat(subFile.findMaxProblemSeverity(IMarker.PROBLEM, true, IResource.DEPTH_INFINITE), - is(IMarker.SEVERITY_INFO)); - assertThat(subFile.findMaxProblemSeverity(IMarker.PROBLEM, false, IResource.DEPTH_ONE), is(IMarker.SEVERITY_INFO)); - assertThat(subFile.findMaxProblemSeverity(IMarker.PROBLEM, true, IResource.DEPTH_ZERO), - is(IMarker.SEVERITY_INFO)); - assertThat(subFile.findMaxProblemSeverity(IMarker.TASK, true, IResource.DEPTH_INFINITE), is(-1)); + assertThat(root.findMaxProblemSeverity(IMarker.PROBLEM, true, IResource.DEPTH_INFINITE)) + .isEqualTo(IMarker.SEVERITY_INFO); + assertThat(root.findMaxProblemSeverity(IMarker.PROBLEM, true, IResource.DEPTH_ONE)).isEqualTo(-1); + assertThat(root.findMaxProblemSeverity(IMarker.PROBLEM, true, IResource.DEPTH_ZERO)).isEqualTo(-1); + assertThat(root.findMaxProblemSeverity(IMarker.TASK, true, IResource.DEPTH_INFINITE)).isEqualTo(-1); + + assertThat(folder.findMaxProblemSeverity(IMarker.PROBLEM, true, IResource.DEPTH_INFINITE)) + .isEqualTo(IMarker.SEVERITY_INFO); + assertThat(folder.findMaxProblemSeverity(IMarker.PROBLEM, true, IResource.DEPTH_ONE)).isEqualTo(-1); + assertThat(folder.findMaxProblemSeverity(IMarker.PROBLEM, true, IResource.DEPTH_ZERO)).isEqualTo(-1); + assertThat(folder.findMaxProblemSeverity(IMarker.TASK, true, IResource.DEPTH_INFINITE)).isEqualTo(-1); + + assertThat(sub.findMaxProblemSeverity(IMarker.PROBLEM, true, IResource.DEPTH_INFINITE)) + .isEqualTo(IMarker.SEVERITY_INFO); + assertThat(sub.findMaxProblemSeverity(IMarker.PROBLEM, true, IResource.DEPTH_ONE)) + .isEqualTo(IMarker.SEVERITY_INFO); + assertThat(sub.findMaxProblemSeverity(IMarker.PROBLEM, true, IResource.DEPTH_ZERO)).isEqualTo(-1); + assertThat(sub.findMaxProblemSeverity(IMarker.TASK, true, IResource.DEPTH_INFINITE)).isEqualTo(-1); + + assertThat(subFile.findMaxProblemSeverity(IMarker.PROBLEM, true, IResource.DEPTH_INFINITE)) + .isEqualTo(IMarker.SEVERITY_INFO); + assertThat(subFile.findMaxProblemSeverity(IMarker.PROBLEM, false, IResource.DEPTH_ONE)) + .isEqualTo(IMarker.SEVERITY_INFO); + assertThat(subFile.findMaxProblemSeverity(IMarker.PROBLEM, true, IResource.DEPTH_ZERO)) + .isEqualTo(IMarker.SEVERITY_INFO); + assertThat(subFile.findMaxProblemSeverity(IMarker.TASK, true, IResource.DEPTH_INFINITE)).isEqualTo(-1); createProblem(topFile, IMarker.SEVERITY_ERROR); - assertThat(root.findMaxProblemSeverity(IMarker.PROBLEM, true, IResource.DEPTH_INFINITE), - is(IMarker.SEVERITY_ERROR)); - assertThat(folder.findMaxProblemSeverity(IMarker.PROBLEM, true, IResource.DEPTH_ONE), - is(IMarker.SEVERITY_ERROR)); - assertThat(topFile.findMaxProblemSeverity(IMarker.PROBLEM, true, IResource.DEPTH_ONE), - is(IMarker.SEVERITY_ERROR)); - assertThat(sub.findMaxProblemSeverity(IMarker.PROBLEM, true, IResource.DEPTH_ONE), is(IMarker.SEVERITY_INFO)); - assertThat(subFile.findMaxProblemSeverity(IMarker.PROBLEM, true, IResource.DEPTH_ZERO), - is(IMarker.SEVERITY_INFO)); + assertThat(root.findMaxProblemSeverity(IMarker.PROBLEM, true, IResource.DEPTH_INFINITE)) + .isEqualTo(IMarker.SEVERITY_ERROR); + assertThat(folder.findMaxProblemSeverity(IMarker.PROBLEM, true, IResource.DEPTH_ONE)) + .isEqualTo(IMarker.SEVERITY_ERROR); + assertThat(topFile.findMaxProblemSeverity(IMarker.PROBLEM, true, IResource.DEPTH_ONE)) + .isEqualTo(IMarker.SEVERITY_ERROR); + assertThat(sub.findMaxProblemSeverity(IMarker.PROBLEM, true, IResource.DEPTH_ONE)) + .isEqualTo(IMarker.SEVERITY_INFO); + assertThat(subFile.findMaxProblemSeverity(IMarker.PROBLEM, true, IResource.DEPTH_ZERO)) + .isEqualTo(IMarker.SEVERITY_INFO); } /** @@ -1021,7 +1026,7 @@ public void testMarkerDeltasMoveProject() throws CoreException { path = path.append(resource.getFullPath().removeFirstSegments(1)); IResource oldResource = ((Workspace) getWorkspace()).newResource(path, resource.getType()); IMarker marker = table.get(oldResource); - assertThat(marker, not(is(nullValue()))); + assertThat(marker).isNotNull(); listener.assertChanges(oldResource, null, new IMarker[] { marker }, null); IMarker[] markers = resource.findMarkers(null, true, IResource.DEPTH_ZERO); assertSingleMarkerWithId(markers, marker.getId()); @@ -1099,7 +1104,7 @@ public String requestName() { // to have assertMarkersExist(expected); IMarker[] actual = getWorkspace().getRoot().findMarkers(null, false, IResource.DEPTH_INFINITE); - assertThat(actual, arrayContainingInAnyOrder(expected)); + assertThat(actual).containsExactlyInAnyOrder(expected); // cleanup assertTrue("deleting file failed", file.delete()); @@ -1188,7 +1193,7 @@ public String requestName() { // to have assertMarkersExist(expected); IMarker[] actual = getWorkspace().getRoot().findMarkers(null, false, IResource.DEPTH_INFINITE); - assertThat(actual, arrayContainingInAnyOrder(expected)); + assertThat(actual).containsExactlyInAnyOrder(expected); // cleanup assertTrue("deleting file failed", file.delete()); @@ -1243,14 +1248,14 @@ public void testSetGetAttribute() throws CoreException { Map originalMap = Map.of(keys[0], values[0], keys[1], values[1], keys[2], values[2]); marker.setAttributes(keys, values); Object[] found = marker.getAttributes(keys); - assertThat(resourcePath, found, is(values)); + assertThat(found).as(resourcePath).isEqualTo(values); marker.setAttribute(IMarker.SEVERITY, null); values[1] = null; found = marker.getAttributes(keys); - assertThat(resourcePath, found, is(values)); + assertThat(found).as(resourcePath).isEqualTo(values); values[1] = Integer.valueOf(5); marker.setAttribute(IMarker.SEVERITY, values[1]); - assertThat(resourcePath, marker.getAttributes(), is(originalMap)); + assertThat(marker.getAttributes()).as(resourcePath).isEqualTo(originalMap); // try sending null as args assertThrows(resourcePath, RuntimeException.class, () -> marker.getAttribute(null)); @@ -1284,7 +1289,7 @@ public void testGetAttributesEquality() throws Exception { // Check the map returned by marker is equal to equal map Map existing = marker.getAttributes(); Map otherAttributes = Map.of(String.valueOf(i), value); - assertThat(otherAttributes, is(existing)); + assertThat(otherAttributes).isEqualTo(existing); } } @@ -1296,17 +1301,17 @@ public void testSetGetAttribute2() throws CoreException { // getting a non-existant attribute should return null or the specified default IMarker marker = resource.createMarker(IMarker.PROBLEM); // #getAttribute(Object) - assertThat(resourcePath, marker.getAttribute(IMarker.MESSAGE), is(nullValue())); + assertThat(marker.getAttribute(IMarker.MESSAGE)).as(resourcePath).isNull(); // #getAttribute(String, String) - assertThat(resourcePath, marker.getAttribute(IMarker.MESSAGE, "default"), is("default")); + assertThat(marker.getAttribute(IMarker.MESSAGE, "default")).as(resourcePath).isEqualTo("default"); // #getAttribute(String, boolean) - assertThat(resourcePath, marker.getAttribute(IMarker.MESSAGE, true), is(true)); + assertThat(marker.getAttribute(IMarker.MESSAGE, true)).as(resourcePath).isTrue(); // #getAttribute(String, int) - assertThat(resourcePath, marker.getAttribute(IMarker.MESSAGE, 5), is(5)); + assertThat(marker.getAttribute(IMarker.MESSAGE, 5)).as(resourcePath).isEqualTo(5); // #getAttributes() - assertThat(resourcePath, marker.getAttributes(), is(nullValue())); + assertThat(marker.getAttributes()).isNull(); // #getAttributes(String[]) - assertThat(resourcePath, marker.getAttributes(new String[] { IMarker.MESSAGE })[0], is(nullValue())); + assertThat(marker.getAttributes(new String[] { IMarker.MESSAGE })[0]).as(resourcePath).isNull(); // set an attribute, get its value, then remove it String testMessage = createRandomString(); @@ -1324,14 +1329,14 @@ public void testSetGetAttribute2() throws CoreException { Map originalMap = Map.of(keys[0], values[0], keys[1], values[1], keys[2], values[2]); marker.setAttributes(keys, values); Object[] found = marker.getAttributes(keys); - assertThat(resourcePath, found, is(values)); + assertThat(found).as(resourcePath).isEqualTo(values); marker.setAttribute(IMarker.SEVERITY, null); values[1] = null; found = marker.getAttributes(keys); - assertThat(resourcePath, found, is(values)); + assertThat(found).as(resourcePath).isEqualTo(values); values[1] = Integer.valueOf(5); marker.setAttribute(IMarker.SEVERITY, values[1]); - assertThat(resourcePath, marker.getAttributes(), is(originalMap)); + assertThat(marker.getAttributes()).as(resourcePath).isEqualTo(originalMap); // try sending null as args assertThrows(resourcePath, RuntimeException.class, () -> marker.getAttribute(null)); @@ -1357,12 +1362,12 @@ public void testSetGetAttribute2() throws CoreException { reretrievedAttributes.put(null, 1); // allowed for clients using IMarker.getAttributes() // not allowed for clients to put null key assertThrows(resourcePath, RuntimeException.class, () -> marker.setAttributes(reretrievedAttributes)); - assertThat(resourcePath, marker.getAttribute("2"), not(is(nullValue()))); - assertThat(resourcePath, marker.getAttributes(), not(is(nullValue()))); + assertThat(marker.getAttribute("2")).as(resourcePath).isNotNull(); + assertThat(marker.getAttributes()).as(resourcePath).isNotNull(); marker.setAttributes(null); - assertThat(resourcePath, marker.getAttribute("1"), is(nullValue())); - assertThat(resourcePath, marker.getAttribute("2"), is(nullValue())); - assertThat(resourcePath, marker.getAttributes(), is(nullValue())); + assertThat(marker.getAttribute("1")).as(resourcePath).isNull(); + assertThat(marker.getAttribute("2")).as(resourcePath).isNull(); + assertThat(marker.getAttributes()).as(resourcePath).isNull(); } } diff --git a/resources/tests/org.eclipse.core.tests.resources/src/org/eclipse/core/tests/resources/MarkersChangeListener.java b/resources/tests/org.eclipse.core.tests.resources/src/org/eclipse/core/tests/resources/MarkersChangeListener.java index b3731403e3c..56a831bd7db 100644 --- a/resources/tests/org.eclipse.core.tests.resources/src/org/eclipse/core/tests/resources/MarkersChangeListener.java +++ b/resources/tests/org.eclipse.core.tests.resources/src/org/eclipse/core/tests/resources/MarkersChangeListener.java @@ -14,10 +14,7 @@ *******************************************************************************/ package org.eclipse.core.tests.resources; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.aMapWithSize; -import static org.hamcrest.Matchers.hasItemInArray; -import static org.hamcrest.Matchers.is; +import static org.assertj.core.api.Assertions.assertThat; import java.util.HashMap; import java.util.List; @@ -51,23 +48,21 @@ public void assertChanges(IResource resource, IMarker[] added, IMarker[] removed v = new Vector<>(); } int numChanges = (added == null ? 0 : added.length) + (removed == null ? 0 : removed.length) + (changed == null ? 0 : changed.length); - assertThat("wrong number of markers for resource " + path, numChanges, is(v.size())); + assertThat(numChanges).as("number of markers for resource %s", path).isEqualTo(v.size()); for (IMarkerDelta delta : v) { switch (delta.getKind()) { - case IResourceDelta.ADDED : - assertThat("added marker is missing resource " + path, added, hasItemInArray(delta.getMarker())); - break; - case IResourceDelta.REMOVED : - assertThat("removed marker is missing resource " + path, removed, - hasItemInArray(delta.getMarker())); - break; - case IResourceDelta.CHANGED : - assertThat("changed marker is missing resource " + path, changed, - hasItemInArray(delta.getMarker())); - break; - default : - throw new IllegalArgumentException("delta with unsupported kind: " + delta); + case IResourceDelta.ADDED: + assertThat(added).as("check added markers contain resource %s", path).contains(delta.getMarker()); + break; + case IResourceDelta.REMOVED: + assertThat(removed).as("check removed markers contain resource %s", path).contains(delta.getMarker()); + break; + case IResourceDelta.CHANGED: + assertThat(changed).as("check changed markers contain resource %s", path).contains(delta.getMarker()); + break; + default: + throw new IllegalArgumentException("delta with unsupported kind: " + delta); } } } @@ -77,7 +72,7 @@ public void assertChanges(IResource resource, IMarker[] added, IMarker[] removed * changes since last reset. */ public void assertNumberOfAffectedResources(int expectedNumberOfResource) { - assertThat(changes, aMapWithSize(expectedNumberOfResource)); + assertThat(changes).hasSize(expectedNumberOfResource); } public void reset() { diff --git a/resources/tests/org.eclipse.core.tests.resources/src/org/eclipse/core/tests/resources/NatureTest.java b/resources/tests/org.eclipse.core.tests.resources/src/org/eclipse/core/tests/resources/NatureTest.java index 56e2e87b946..798dddfaf0a 100644 --- a/resources/tests/org.eclipse.core.tests.resources/src/org/eclipse/core/tests/resources/NatureTest.java +++ b/resources/tests/org.eclipse.core.tests.resources/src/org/eclipse/core/tests/resources/NatureTest.java @@ -13,6 +13,7 @@ *******************************************************************************/ package org.eclipse.core.tests.resources; +import static org.assertj.core.api.Assertions.assertThat; import static org.eclipse.core.tests.resources.ResourceTestPluginConstants.NATURE_127562; import static org.eclipse.core.tests.resources.ResourceTestPluginConstants.NATURE_EARTH; import static org.eclipse.core.tests.resources.ResourceTestPluginConstants.NATURE_MISSING; @@ -24,12 +25,6 @@ import static org.eclipse.core.tests.resources.ResourceTestUtil.createInWorkspace; import static org.eclipse.core.tests.resources.ResourceTestUtil.createTestMonitor; import static org.eclipse.core.tests.resources.ResourceTestUtil.createUniqueString; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.arrayWithSize; -import static org.hamcrest.Matchers.emptyArray; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.not; -import static org.hamcrest.Matchers.nullValue; import static org.junit.Assert.assertThrows; import java.io.ByteArrayInputStream; @@ -125,17 +120,17 @@ public void setUp() throws Exception { } private void assertHasEnabledNature(String nature) throws CoreException { - assertThat("project '" + project + "' is expected to have nature: " + nature, - project.hasNature(nature)); - assertThat("project '" + project + "' is expected to have nature enabled: " + nature, - project.isNatureEnabled(nature)); + assertThat(project.hasNature(nature)) + .withFailMessage("project '%s' is expected to have nature: %s", project, nature).isTrue(); + assertThat(project.isNatureEnabled(nature)) + .withFailMessage("project '%s' is expected to have nature enabled: %s", project, nature).isTrue(); } private void assertDoesNotHaveNature(String nature) throws CoreException { - assertThat("project '" + project + "' is not expected to have nature: " + nature, - !project.hasNature(nature)); - assertThat("project '" + project + "' is not expected to have nature enabled: " + nature, - !project.isNatureEnabled(nature)); + assertThat(project.hasNature(nature)) + .withFailMessage("project '%s' is not expected to have nature: %s", project, nature).isFalse(); + assertThat(project.isNatureEnabled(nature)) + .withFailMessage("project '%s' is not expected to have nature enabled: %s", project, nature).isFalse(); } /** @@ -184,30 +179,30 @@ public void testNatureLifecyle() throws Throwable { //add simple nature setNatures(project, new String[] { NATURE_SIMPLE }, false); SimpleNature instance = SimpleNature.getInstance(); - assertThat("Simple nature has not been configured", instance.wasConfigured); - assertThat("Simple nature has been deconfigured", !instance.wasDeconfigured); + assertThat(instance.wasConfigured).withFailMessage("Simple nature has not been configured").isTrue(); + assertThat(instance.wasDeconfigured).withFailMessage("Simple nature has been deconfigured").isFalse(); instance.reset(); //remove simple nature setNatures(project, new String[0], false); instance = SimpleNature.getInstance(); - assertThat("Simple nature has been configured", !instance.wasConfigured); - assertThat("Simple nature has not been deconfigured", instance.wasDeconfigured); + assertThat(instance.wasConfigured).withFailMessage("Simple nature has been configured").isFalse(); + assertThat(instance.wasDeconfigured).withFailMessage("Simple nature has not been deconfigured").isTrue(); //add with AVOID_NATURE_CONFIG instance.reset(); setNatures(project, new String[] { NATURE_SIMPLE }, false, true); instance = SimpleNature.getInstance(); - assertThat("Simple nature has been configured", !instance.wasConfigured); - assertThat("Simple nature has been deconfigured", !instance.wasDeconfigured); + assertThat(instance.wasConfigured).withFailMessage("Simple nature has been configured").isFalse(); + assertThat(instance.wasDeconfigured).withFailMessage("Simple nature has been deconfigured").isFalse(); assertHasEnabledNature(NATURE_SIMPLE); //remove with AVOID_NATURE_CONFIG instance.reset(); setNatures(project, new String[0], false, true); instance = SimpleNature.getInstance(); - assertThat("Simple nature has been configured", !instance.wasConfigured); - assertThat("Simple nature has been deconfigured", !instance.wasDeconfigured); + assertThat(instance.wasConfigured).withFailMessage("Simple nature has been configured").isFalse(); + assertThat(instance.wasDeconfigured).withFailMessage("Simple nature has been deconfigured").isFalse(); assertDoesNotHaveNature(NATURE_SIMPLE); } @@ -232,7 +227,7 @@ public void testSimpleNature() throws Throwable { setNatures(project, element, true); assertHasEnabledNature(NATURE_SIMPLE); assertDoesNotHaveNature(NATURE_WATER); - assertThat(currentSet, is(project.getDescription().getNatureIds())); + assertThat(currentSet).isEqualTo(project.getDescription().getNatureIds()); } } @@ -285,7 +280,7 @@ public void testBug297871() throws Throwable { setNatures(project, new String[] { NATURE_EARTH }, false); assertHasEnabledNature(NATURE_EARTH); - assertThat(project.getNature(NATURE_EARTH), not(nullValue())); + assertThat(project.getNature(NATURE_EARTH)).isNotNull(); // Make sure enough time has past to bump file's // timestamp during the copy @@ -295,7 +290,7 @@ public void testBug297871() throws Throwable { project.refreshLocal(IResource.DEPTH_INFINITE, createTestMonitor()); assertDoesNotHaveNature(NATURE_EARTH); - assertThat(project.getNature(NATURE_EARTH), nullValue()); + assertThat(project.getNature(NATURE_EARTH)).isNull(); } private void copy(java.io.File src, java.io.File dst) throws IOException { @@ -381,15 +376,15 @@ public void testMissingNatureAddsMarker() throws Exception { Job.getJobManager().wakeUp(CheckMissingNaturesListener.MARKER_TYPE); Job.getJobManager().join(CheckMissingNaturesListener.MARKER_TYPE, createTestMonitor()); IMarker[] markers = project.findMarkers(CheckMissingNaturesListener.MARKER_TYPE, false, IResource.DEPTH_ONE); - assertThat(markers, arrayWithSize(1)); + assertThat(markers).hasSize(1); IMarker marker = markers[0]; - assertThat(marker.getAttribute("natureId"), is(NATURE_MISSING)); - assertThat(marker.getAttribute(IMarker.CHAR_START, -42), not(-42)); - assertThat(marker.getAttribute(IMarker.CHAR_END, -42), not(-42)); + assertThat(marker.getAttribute("natureId")).isEqualTo(NATURE_MISSING); + assertThat(marker.getAttribute(IMarker.CHAR_START, -42)).isNotEqualTo(-42); + assertThat(marker.getAttribute(IMarker.CHAR_END, -42)).isNotEqualTo(-42); try (ByteArrayOutputStream bos = new ByteArrayOutputStream(); InputStream input = ((IFile) marker.getResource()).getContents()) { FileUtil.transferStreams(input, bos, "whatever", createTestMonitor()); String marked = bos.toString().substring(marker.getAttribute(IMarker.CHAR_START, -42), marker.getAttribute(IMarker.CHAR_END, -42)); - assertThat(marked, is(NATURE_MISSING)); + assertThat(marked).isEqualTo(NATURE_MISSING); } } @@ -405,16 +400,16 @@ public void testMissingNatureWithWhitespacesSetChars() throws Exception { Job.getJobManager().wakeUp(CheckMissingNaturesListener.MARKER_TYPE); Job.getJobManager().join(CheckMissingNaturesListener.MARKER_TYPE, createTestMonitor()); IMarker[] markers = project.findMarkers(CheckMissingNaturesListener.MARKER_TYPE, false, IResource.DEPTH_ONE); - assertThat(markers, arrayWithSize(1)); + assertThat(markers).hasSize(1); IMarker marker = markers[0]; - assertThat(marker.getAttribute("natureId"), is(NATURE_MISSING)); - assertThat(marker.getAttribute(IMarker.CHAR_START, -42), not(-42)); - assertThat(marker.getAttribute(IMarker.CHAR_END, -42), not(-42)); + assertThat(marker.getAttribute("natureId")).isEqualTo(NATURE_MISSING); + assertThat(marker.getAttribute(IMarker.CHAR_START, -42)).isNotEqualTo(-42); + assertThat(marker.getAttribute(IMarker.CHAR_END, -42)).isNotEqualTo(-42); try (ByteArrayOutputStream bos = new ByteArrayOutputStream(); InputStream input = ((IFile) marker.getResource()).getContents()) { FileUtil.transferStreams(input, bos, "whatever", createTestMonitor()); String marked = bos.toString().substring(marker.getAttribute(IMarker.CHAR_START, -42), marker.getAttribute(IMarker.CHAR_END, -42)); - assertThat(marked, is(NATURE_MISSING)); + assertThat(marked).isEqualTo(NATURE_MISSING); } } @@ -430,8 +425,7 @@ public void testKnownNatureDoesntAddMarker() throws Exception { project.build(IncrementalProjectBuilder.FULL_BUILD, createTestMonitor()); Job.getJobManager().wakeUp(CheckMissingNaturesListener.MARKER_TYPE); Job.getJobManager().join(CheckMissingNaturesListener.MARKER_TYPE, createTestMonitor()); - assertThat(project.findMarkers(CheckMissingNaturesListener.MARKER_TYPE, false, IResource.DEPTH_ONE), - emptyArray()); + assertThat(project.findMarkers(CheckMissingNaturesListener.MARKER_TYPE, false, IResource.DEPTH_ONE)).isEmpty(); } @Test @@ -443,23 +437,23 @@ public void testListenToPreferenceChange() throws Exception { Job.getJobManager().wakeUp(CheckMissingNaturesListener.MARKER_TYPE); Job.getJobManager().join(CheckMissingNaturesListener.MARKER_TYPE, createTestMonitor()); IMarker[] markers = project.findMarkers(CheckMissingNaturesListener.MARKER_TYPE, false, IResource.DEPTH_ONE); - assertThat(markers, arrayWithSize(1)); - assertThat(markers[0].getAttribute(IMarker.SEVERITY, -42), is(IMarker.SEVERITY_INFO)); + assertThat(markers).hasSize(1).satisfiesExactly( + marker -> assertThat(marker.getAttribute(IMarker.SEVERITY, -42)).isEqualTo(IMarker.SEVERITY_INFO)); // to IGNORE InstanceScope.INSTANCE.getNode(ResourcesPlugin.PI_RESOURCES).putInt(ResourcesPlugin.PREF_MISSING_NATURE_MARKER_SEVERITY, -1); InstanceScope.INSTANCE.getNode(ResourcesPlugin.PI_RESOURCES).flush(); Job.getJobManager().wakeUp(CheckMissingNaturesListener.MARKER_TYPE); Job.getJobManager().join(CheckMissingNaturesListener.MARKER_TYPE, createTestMonitor()); markers = project.findMarkers(CheckMissingNaturesListener.MARKER_TYPE, false, IResource.DEPTH_ONE); - assertThat(markers, arrayWithSize(0)); + assertThat(markers).isEmpty(); // to ERROR InstanceScope.INSTANCE.getNode(ResourcesPlugin.PI_RESOURCES).putInt(ResourcesPlugin.PREF_MISSING_NATURE_MARKER_SEVERITY, IMarker.SEVERITY_ERROR); InstanceScope.INSTANCE.getNode(ResourcesPlugin.PI_RESOURCES).flush(); Job.getJobManager().wakeUp(CheckMissingNaturesListener.MARKER_TYPE); Job.getJobManager().join(CheckMissingNaturesListener.MARKER_TYPE, createTestMonitor()); markers = project.findMarkers(CheckMissingNaturesListener.MARKER_TYPE, false, IResource.DEPTH_ONE); - assertThat(markers, arrayWithSize(1)); - assertThat(markers[0].getAttribute(IMarker.SEVERITY, -42), is(IMarker.SEVERITY_ERROR)); + assertThat(markers).hasSize(1).satisfiesExactly( + marker -> assertThat(marker.getAttribute(IMarker.SEVERITY, -42)).isEqualTo(IMarker.SEVERITY_ERROR)); } } diff --git a/resources/tests/org.eclipse.core.tests.resources/src/org/eclipse/core/tests/resources/ResourceTestUtil.java b/resources/tests/org.eclipse.core.tests.resources/src/org/eclipse/core/tests/resources/ResourceTestUtil.java index df291dee798..c150543309e 100644 --- a/resources/tests/org.eclipse.core.tests.resources/src/org/eclipse/core/tests/resources/ResourceTestUtil.java +++ b/resources/tests/org.eclipse.core.tests.resources/src/org/eclipse/core/tests/resources/ResourceTestUtil.java @@ -12,10 +12,8 @@ package org.eclipse.core.tests.resources; import static java.io.InputStream.nullInputStream; +import static org.assertj.core.api.Assertions.assertThat; import static org.eclipse.core.resources.ResourcesPlugin.getWorkspace; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.not; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; @@ -435,7 +433,8 @@ public static boolean isReadOnlySupported() { * Sets the read-only state of the given file store to {@code value}. */ public static void setReadOnly(IFileStore target, boolean value) throws CoreException { - assertThat("Setting read only is not supported by local file system", isReadOnlySupported()); + assertThat(isReadOnlySupported()).withFailMessage("setting read only is not supported by local file system") + .isTrue(); IFileInfo fileInfo = target.fetchInfo(); fileInfo.setAttribute(EFS.ATTRIBUTE_READ_ONLY, value); target.putInfo(fileInfo, EFS.SET_ATTRIBUTES, null); @@ -487,8 +486,6 @@ public static void ensureOutOfSync(final IFile file) throws CoreException, IOExc modifyInFileSystem(file); waitForRefresh(); touchInFilesystem(file); - assertThat("file not out of sync: " + file.getLocation().toOSString(), file.getLocalTimeStamp(), - not(is(file.getLocation().toFile().lastModified()))); } private static void modifyInFileSystem(IFile file) throws FileNotFoundException, IOException { @@ -532,8 +529,8 @@ public static void touchInFilesystem(IResource resource) throws CoreException, I } } } - assertThat("File not out of sync: " + location.toOSString(), resource.getLocalTimeStamp(), - not(is(getLastModifiedTime(location)))); + assertThat(resource.getLocalTimeStamp()).as("file not out of sync: %s", location.toOSString()) + .isNotEqualTo(getLastModifiedTime(location)); } private static boolean isInSync(IResource resource) { diff --git a/resources/tests/org.eclipse.core.tests.resources/src/org/eclipse/core/tests/resources/TeamPrivateMemberTest.java b/resources/tests/org.eclipse.core.tests.resources/src/org/eclipse/core/tests/resources/TeamPrivateMemberTest.java index 37f40403f3c..b47d84d3299 100644 --- a/resources/tests/org.eclipse.core.tests.resources/src/org/eclipse/core/tests/resources/TeamPrivateMemberTest.java +++ b/resources/tests/org.eclipse.core.tests.resources/src/org/eclipse/core/tests/resources/TeamPrivateMemberTest.java @@ -13,6 +13,7 @@ *******************************************************************************/ package org.eclipse.core.tests.resources; +import static org.assertj.core.api.Assertions.assertThat; import static org.eclipse.core.resources.ResourcesPlugin.getWorkspace; import static org.eclipse.core.tests.resources.ResourceTestUtil.assertDoesNotExistInWorkspace; import static org.eclipse.core.tests.resources.ResourceTestUtil.assertExistsInWorkspace; @@ -21,9 +22,6 @@ import static org.eclipse.core.tests.resources.ResourceTestUtil.ensureOutOfSync; import static org.eclipse.core.tests.resources.ResourceTestUtil.removeFromWorkspace; import static org.eclipse.core.tests.resources.ResourceTestUtil.waitForBuild; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.arrayWithSize; -import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThrows; import static org.junit.Assert.assertTrue; @@ -83,24 +81,24 @@ public void testFindMember() throws CoreException { createInWorkspace(resources); // no team private members - assertThat(root.findMember(project.getFullPath()), is(project)); - assertThat(root.findMember(folder.getFullPath()), is(folder)); - assertThat(root.findMember(file.getFullPath()), is(file)); - assertThat(root.findMember(subFile.getFullPath()), is(subFile)); + assertThat(root.findMember(project.getFullPath())).isEqualTo(project); + assertThat(root.findMember(folder.getFullPath())).isEqualTo(folder); + assertThat(root.findMember(file.getFullPath())).isEqualTo(file); + assertThat(root.findMember(subFile.getFullPath())).isEqualTo(subFile); // the folder is team private setTeamPrivateMember(folder, true, IResource.DEPTH_ZERO); - assertThat(root.findMember(project.getFullPath()), is(project)); - assertThat(root.findMember(folder.getFullPath()), is(folder)); - assertThat(root.findMember(file.getFullPath()), is(file)); - assertThat(root.findMember(subFile.getFullPath()), is(subFile)); + assertThat(root.findMember(project.getFullPath())).isEqualTo(project); + assertThat(root.findMember(folder.getFullPath())).isEqualTo(folder); + assertThat(root.findMember(file.getFullPath())).isEqualTo(file); + assertThat(root.findMember(subFile.getFullPath())).isEqualTo(subFile); // all are team private setTeamPrivateMember(project, true, IResource.DEPTH_INFINITE); - assertThat(root.findMember(project.getFullPath()), is(project)); - assertThat(root.findMember(folder.getFullPath()), is(folder)); - assertThat(root.findMember(file.getFullPath()), is(file)); - assertThat(root.findMember(subFile.getFullPath()), is(subFile)); + assertThat(root.findMember(project.getFullPath())).isEqualTo(project); + assertThat(root.findMember(folder.getFullPath())).isEqualTo(folder); + assertThat(root.findMember(file.getFullPath())).isEqualTo(file); + assertThat(root.findMember(subFile.getFullPath())).isEqualTo(subFile); } /** @@ -123,8 +121,8 @@ public void testMembers() throws CoreException { // Check the calls to #members // +1 for the project description file - assertThat(project.members(), arrayWithSize(4)); - assertThat(folder.members(), arrayWithSize(1)); + assertThat(project.members()).hasSize(4); + assertThat(folder.members()).hasSize(1); // Set the values. setTeamPrivateMember(project, true, IResource.DEPTH_INFINITE); @@ -134,8 +132,8 @@ public void testMembers() throws CoreException { assertTeamPrivateMember(project, true, IResource.DEPTH_INFINITE); // Check the calls to #members - assertThat(project.members(), arrayWithSize(0)); - assertThat(folder.members(), arrayWithSize(0)); + assertThat(project.members()).hasSize(0); + assertThat(folder.members()).hasSize(0); // reset to false setTeamPrivateMember(project, false, IResource.DEPTH_INFINITE); @@ -143,30 +141,30 @@ public void testMembers() throws CoreException { // Check the calls to members(IResource.NONE); // +1 for the project description file - assertThat(project.members(IResource.NONE), arrayWithSize(4)); + assertThat(project.members(IResource.NONE)).hasSize(4); // +1 for the project description file - assertThat(project.members(IContainer.INCLUDE_TEAM_PRIVATE_MEMBERS), arrayWithSize(4)); - assertThat(folder.members(), arrayWithSize(1)); + assertThat(project.members(IContainer.INCLUDE_TEAM_PRIVATE_MEMBERS)).hasSize(4); + assertThat(folder.members()).hasSize(1); // Set one of the children to be TEAM_PRIVATE and try again setTeamPrivateMember(folder, true, IResource.DEPTH_ZERO); // +1 for project description, -1 for team private folder - assertThat(project.members(), arrayWithSize(3)); - assertThat(folder.members(), arrayWithSize(1)); + assertThat(project.members()).hasSize(3); + assertThat(folder.members()).hasSize(1); // +1 for project description, -1 for team private folder - assertThat(project.members(IResource.NONE), arrayWithSize(3)); - assertThat(folder.members(), arrayWithSize(1)); + assertThat(project.members(IResource.NONE)).hasSize(3); + assertThat(folder.members()).hasSize(1); // +1 for project description - assertThat(project.members(IContainer.INCLUDE_TEAM_PRIVATE_MEMBERS), arrayWithSize(4)); - assertThat(folder.members(), arrayWithSize(1)); + assertThat(project.members(IContainer.INCLUDE_TEAM_PRIVATE_MEMBERS)).hasSize(4); + assertThat(folder.members()).hasSize(1); // Set all the resources to be team private setTeamPrivateMember(project, true, IResource.DEPTH_INFINITE); assertTeamPrivateMember(project, true, IResource.DEPTH_INFINITE); - assertThat(project.members(IResource.NONE), arrayWithSize(0)); - assertThat(folder.members(IResource.NONE), arrayWithSize(0)); - assertThat(project.members(IContainer.INCLUDE_TEAM_PRIVATE_MEMBERS), arrayWithSize(4)); - assertThat(folder.members(IContainer.INCLUDE_TEAM_PRIVATE_MEMBERS), arrayWithSize(1)); + assertThat(project.members(IResource.NONE)).hasSize(0); + assertThat(folder.members(IResource.NONE)).hasSize(0); + assertThat(project.members(IContainer.INCLUDE_TEAM_PRIVATE_MEMBERS)).hasSize(4); + assertThat(folder.members(IContainer.INCLUDE_TEAM_PRIVATE_MEMBERS)).hasSize(1); } /** @@ -592,8 +590,8 @@ private void assertTeamPrivateMember(IResource root, final boolean value, int de } private void assertTeamPrivateMember(IResource resource, boolean expectedValue) { - assertThat("unexpected isTeamPrivateMember value for resource: " + resource, resource.isTeamPrivateMember(), - is(expectedValue)); + assertThat(resource.isTeamPrivateMember()) + .as("isTeamPrivateMember value for resource: %s", resource).isEqualTo(expectedValue); } private void setTeamPrivateMember(IResource root, final boolean value, int depth) diff --git a/resources/tests/org.eclipse.core.tests.resources/src/org/eclipse/core/tests/resources/refresh/RefreshProviderTest.java b/resources/tests/org.eclipse.core.tests.resources/src/org/eclipse/core/tests/resources/refresh/RefreshProviderTest.java index 23fa765b5fc..22540291df5 100644 --- a/resources/tests/org.eclipse.core.tests.resources/src/org/eclipse/core/tests/resources/refresh/RefreshProviderTest.java +++ b/resources/tests/org.eclipse.core.tests.resources/src/org/eclipse/core/tests/resources/refresh/RefreshProviderTest.java @@ -13,14 +13,12 @@ *******************************************************************************/ package org.eclipse.core.tests.resources.refresh; +import static org.assertj.core.api.Assertions.assertThat; import static org.eclipse.core.resources.ResourcesPlugin.getWorkspace; import static org.eclipse.core.tests.harness.FileSystemHelper.getRandomLocation; import static org.eclipse.core.tests.resources.ResourceTestUtil.createInWorkspace; import static org.eclipse.core.tests.resources.ResourceTestUtil.createTestMonitor; import static org.eclipse.core.tests.resources.ResourceTestUtil.removeFromWorkspace; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.anEmptyMap; -import static org.hamcrest.Matchers.emptyArray; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; @@ -103,7 +101,7 @@ public void testLinkedFile() throws Exception { assertEquals("1.3", 0, provider.getMonitoredResources().length); // check provider for other errors AssertionFailedError[] failures = provider.getFailures(); - assertThat(failures, emptyArray()); + assertThat(failures).isEmpty(); } /** @@ -130,7 +128,7 @@ public void testProjectCloseOpen() throws Exception { assertEquals("1.3", 0, provider.getMonitoredResources().length); // check provider for other errors AssertionFailedError[] failures = provider.getFailures(); - assertThat(failures, emptyArray()); + assertThat(failures).isEmpty(); } /** @@ -154,7 +152,7 @@ public void testProjectCreateDelete() throws Exception { fails.put(i, e); } } - assertThat(fails, anEmptyMap()); + assertThat(fails).isEmpty(); } private IProject createProject(String name) throws Exception { diff --git a/resources/tests/org.eclipse.core.tests.resources/src/org/eclipse/core/tests/resources/session/Bug_266907.java b/resources/tests/org.eclipse.core.tests.resources/src/org/eclipse/core/tests/resources/session/Bug_266907.java index 0f52e4e2e3d..9e95e9f3bb4 100644 --- a/resources/tests/org.eclipse.core.tests.resources/src/org/eclipse/core/tests/resources/session/Bug_266907.java +++ b/resources/tests/org.eclipse.core.tests.resources/src/org/eclipse/core/tests/resources/session/Bug_266907.java @@ -13,13 +13,13 @@ *******************************************************************************/ package org.eclipse.core.tests.resources.session; +import static java.util.function.Predicate.not; +import static org.assertj.core.api.Assertions.assertThat; import static org.eclipse.core.resources.ResourcesPlugin.getWorkspace; import static org.eclipse.core.tests.harness.FileSystemHelper.getTempDir; import static org.eclipse.core.tests.resources.ResourceTestPluginConstants.PI_RESOURCES_TESTS; import static org.eclipse.core.tests.resources.ResourceTestUtil.createInputStream; import static org.eclipse.core.tests.resources.ResourceTestUtil.createTestMonitor; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.MatcherAssert.assertThat; import java.io.File; import java.io.FileInputStream; @@ -86,7 +86,7 @@ public void test2RestoreWorkspaceFile() throws Exception { IProject project = workspace.getRoot().getProject(PROJECT_NAME); // the project should be closed cause .project is removed - assertThat("project should not be accessible", project.isAccessible(), is(false)); + assertThat(project).matches(not(IProject::isAccessible), "is not accessible"); // recreate .project File dotProject = project.getFile(".project").getLocation().toFile(); @@ -100,14 +100,14 @@ public void test2RestoreWorkspaceFile() throws Exception { dotProjectCopy.delete(); project.open(createTestMonitor()); - assertThat("project should be accessible", project.isAccessible(), is(true)); + assertThat(project).matches(IProject::isAccessible, "is accessible"); IFile file = project.getFile(FILE_NAME); IMarker[] markers = file.findMarkers(IMarker.BOOKMARK, false, IResource.DEPTH_ZERO); - assertThat("unexpected number of markers in test project", markers.length, is(1)); + assertThat(markers).as("number of markers").hasSize(1); Object attribute = markers[0].getAttribute(MARKER_ATTRIBUTE_NAME); - assertThat("unexpected name of marker", attribute, is(MARKER_ATTRIBUTE)); + assertThat(attribute).as("name of marker").isEqualTo(MARKER_ATTRIBUTE); } } diff --git a/resources/tests/org.eclipse.core.tests.resources/src/org/eclipse/core/tests/resources/session/ProjectDescriptionDynamicTest.java b/resources/tests/org.eclipse.core.tests.resources/src/org/eclipse/core/tests/resources/session/ProjectDescriptionDynamicTest.java index d40c0b8eda7..10cb1645c00 100644 --- a/resources/tests/org.eclipse.core.tests.resources/src/org/eclipse/core/tests/resources/session/ProjectDescriptionDynamicTest.java +++ b/resources/tests/org.eclipse.core.tests.resources/src/org/eclipse/core/tests/resources/session/ProjectDescriptionDynamicTest.java @@ -13,12 +13,10 @@ ******************************************************************************/ package org.eclipse.core.tests.resources.session; +import static org.assertj.core.api.Assertions.assertThat; import static org.eclipse.core.resources.ResourcesPlugin.getWorkspace; import static org.eclipse.core.tests.resources.ResourceTestPluginConstants.PI_RESOURCES_TESTS; import static org.eclipse.core.tests.resources.ResourceTestUtil.createTestMonitor; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.emptyArray; -import static org.hamcrest.Matchers.is; import junit.framework.Test; import org.eclipse.core.resources.IBuildConfiguration; @@ -99,10 +97,10 @@ public void test1() throws Exception { * - project level references still exist */ public void test2() throws Exception { - assertThat("project is unexpectedly not accessible: " + proj, proj.isAccessible()); - assertThat(dynRefs, is(proj.getDescription().getDynamicReferences())); - assertThat(proj.getBuildConfigs(), is(configs)); - assertThat(proj.getActiveBuildConfig(), is(configs[0])); + assertThat(proj).matches(IProject::isAccessible, "is accessible"); + assertThat(proj.getDescription().getDynamicReferences()).isEqualTo(dynRefs); + assertThat(proj.getBuildConfigs()).isEqualTo(configs); + assertThat(proj.getActiveBuildConfig()).isEqualTo(configs[0]); // set build configuration level dynamic references on the project IProjectDescription desc = proj.getDescription(); @@ -121,20 +119,20 @@ public void test2() throws Exception { * - Build config references are correct */ public void test3() throws Exception { - assertThat("project is unexpectedly not accessible: " + proj, proj.isAccessible()); - assertThat(proj.getActiveBuildConfig(), is(configs[1])); + assertThat(proj).matches(IProject::isAccessible, "is accessible"); + assertThat(proj.getActiveBuildConfig()).isEqualTo(configs[1]); // At description dynamic refs are what was set - assertThat(proj.getDescription().getDynamicReferences(), is(dynRefs)); + assertThat(proj.getDescription().getDynamicReferences()).isEqualTo(dynRefs); // At project all references are union of build configuration and project references - assertThat(proj.getReferencedProjects(), is(configRefsProjects)); + assertThat(proj.getReferencedProjects()).isEqualTo(configRefsProjects); // At the description level, dynamic config references match what was set. - assertThat(proj.getDescription().getBuildConfigReferences(configs[1].getName()), is(configRefs)); + assertThat(proj.getDescription().getBuildConfigReferences(configs[1].getName())).isEqualTo(configRefs); // At the project level, references are the union of project and build configuration level references IBuildConfiguration[] refs = new IBuildConfiguration[] {configRefs[0], configRefs[1], configRefs[2], getRef(dynRefs[0]), getRef(dynRefs[1])}; - assertThat(proj.getReferencedBuildConfigs(configs[1].getName(), true), is(refs)); + assertThat(proj.getReferencedBuildConfigs(configs[1].getName(), true)).isEqualTo(refs); // No other projects exist, so check references are empty if we want to filter empty projects - assertThat(proj.getReferencedBuildConfigs(configs[1].getName(), false), emptyArray()); + assertThat(proj.getReferencedBuildConfigs(configs[1].getName(), false)).isEmpty(); } public static Test suite() { diff --git a/resources/tests/org.eclipse.core.tests.resources/src/org/eclipse/core/tests/resources/session/WorkspaceDescriptionTest.java b/resources/tests/org.eclipse.core.tests.resources/src/org/eclipse/core/tests/resources/session/WorkspaceDescriptionTest.java index b916127cf1b..df183d6c442 100644 --- a/resources/tests/org.eclipse.core.tests.resources/src/org/eclipse/core/tests/resources/session/WorkspaceDescriptionTest.java +++ b/resources/tests/org.eclipse.core.tests.resources/src/org/eclipse/core/tests/resources/session/WorkspaceDescriptionTest.java @@ -13,10 +13,10 @@ *******************************************************************************/ package org.eclipse.core.tests.resources.session; +import static java.util.function.Predicate.not; +import static org.assertj.core.api.Assertions.assertThat; import static org.eclipse.core.tests.resources.ResourceTestPluginConstants.PI_RESOURCES_TESTS; import static org.eclipse.core.tests.resources.ResourceTestUtil.createTestMonitor; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.is; import junit.framework.Test; import org.eclipse.core.resources.IWorkspace; @@ -55,13 +55,15 @@ public void test1() throws CoreException { public void test2() { IWorkspace workspace = ResourcesPlugin.getWorkspace(); IWorkspaceDescription desc = workspace.getDescription(); - assertThat("auto building is expected to be disabled: " + desc, !desc.isAutoBuilding()); - assertThat("unexpected buildorder in: " + desc, desc.getBuildOrder(), is(BUILD_ORDER)); - assertThat("unexpected apply file state policy in: " + desc, desc.isApplyFileStatePolicy(), is(APPLY_POLICY)); - assertThat("unexpected longevity in: " + desc, desc.getFileStateLongevity(), is(STATE_LONGEVITY)); - assertThat("unexpected max states in: " + desc, desc.getMaxFileStates(), is(MAX_STATES)); - assertThat("unexpected max file size in: " + desc, desc.getMaxFileStateSize(), is(MAX_FILE_SIZE)); - assertThat("unexpected snapshot interval in: " + desc, desc.getSnapshotInterval(), is(SNAPSHOT_INTERVAL)); + assertThat(desc).matches(not(IWorkspaceDescription::isAutoBuilding), "auto building is disabled"); + assertThat(desc.getBuildOrder()).as("buildorder in: %s", desc).isEqualTo(BUILD_ORDER); + assertThat(desc.isApplyFileStatePolicy()).as("apply file state policy in: %s", desc) + .isEqualTo(APPLY_POLICY); + assertThat(desc.getFileStateLongevity()).as("longevity in: %s", desc).isEqualTo(STATE_LONGEVITY); + assertThat(desc.getMaxFileStates()).as("max states in: %s", desc).isEqualTo(MAX_STATES); + assertThat(desc.getMaxFileStateSize()).as("max file size in: %s", desc).isEqualTo(MAX_FILE_SIZE); + assertThat(desc.getSnapshotInterval()).as("snapshot interval in: %s", desc) + .isEqualTo(SNAPSHOT_INTERVAL); } public static Test suite() { diff --git a/resources/tests/org.eclipse.core.tests.resources/src/org/eclipse/core/tests/resources/usecase/IFileTest.java b/resources/tests/org.eclipse.core.tests.resources/src/org/eclipse/core/tests/resources/usecase/IFileTest.java index f564a9ed6b0..52660da24ea 100644 --- a/resources/tests/org.eclipse.core.tests.resources/src/org/eclipse/core/tests/resources/usecase/IFileTest.java +++ b/resources/tests/org.eclipse.core.tests.resources/src/org/eclipse/core/tests/resources/usecase/IFileTest.java @@ -13,6 +13,8 @@ *******************************************************************************/ package org.eclipse.core.tests.resources.usecase; +import static java.util.function.Predicate.not; +import static org.assertj.core.api.Assertions.assertThat; import static org.eclipse.core.resources.ResourcesPlugin.getWorkspace; import static org.eclipse.core.tests.resources.ResourceTestUtil.createInputStream; import static org.eclipse.core.tests.resources.usecase.IResourceTestUtil.FILE; @@ -22,10 +24,6 @@ import static org.eclipse.core.tests.resources.usecase.IResourceTestUtil.STRING_VALUE; import static org.eclipse.core.tests.resources.usecase.IResourceTestUtil.commonFailureTestsForResource; import static org.eclipse.core.tests.resources.usecase.IResourceTestUtil.isLocal; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.arrayWithSize; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.nullValue; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IFolder; @@ -51,11 +49,9 @@ public class IFileTest { */ protected void nonexistentFileFailureTests(IFile file, IWorkspace wb) { /* Tests for failure in get/set methods in IResource. */ - assertThat("file is unexpectedly available locally: " + file, !isLocal(file, IResource.DEPTH_ZERO)); - assertThat("file and its direct children are unexpectedly available locally: " + file, - !isLocal(file, IResource.DEPTH_ONE)); - assertThat("file and all its children are unexpectedly available locally: " + file, - !isLocal(file, IResource.DEPTH_INFINITE)); + assertThat(file).matches(it -> !isLocal(it, IResource.DEPTH_ZERO), "is not local") + .matches(it -> !isLocal(it, IResource.DEPTH_ONE), "is not local with direct children") + .matches(it -> !isLocal(it, IResource.DEPTH_INFINITE), "is not local with all children"); commonFailureTestsForResource(file, false); } @@ -89,30 +85,29 @@ public void testFile() throws CoreException { // Construct a file handle IFile file = folder.getFile(IPath.fromOSString(FILE)); - // Inspection methods with meaninful results invoked on a handle for a nonexistent folder. - assertThat("file does not exist: " + file, !file.exists()); - assertThat(file.getWorkspace(), is(workspace)); - assertThat(file.getProject(), is(proj)); - assertThat(file.getParent(), is(folder)); - assertThat(file.getType(), is(IResource.FILE)); - assertThat(file.getFullPath(), is(IPath.fromOSString("/" + PROJECT + "/" + FOLDER + "/" + FILE))); - assertThat(file.getName(), is(FILE)); - assertThat(proj.getFolder(IPath.fromOSString(FOLDER)), is(folder)); - assertThat(workspace.getRoot().getFile(file.getFullPath()), is(file)); + // Inspection methods with meaningful results invoked on a handle for a nonexistent folder. + assertThat(file).matches(not(IFile::exists), "does not exist"); + assertThat(file.getWorkspace()).isEqualTo(workspace); + assertThat(file.getProject()).isEqualTo(proj); + assertThat(file.getParent()).isEqualTo(folder); + assertThat(file.getType()).isEqualTo(IResource.FILE); + assertThat(file.getFullPath()).isEqualTo(IPath.fromOSString("/" + PROJECT + "/" + FOLDER + "/" + FILE)); + assertThat(file.getName()).isEqualTo(FILE); + assertThat(proj.getFolder(IPath.fromOSString(FOLDER))).isEqualTo(folder); + assertThat(workspace.getRoot().getFile(file.getFullPath())).isEqualTo(file); IPath projRelativePath = IPath.fromOSString(FOLDER + "/" + FILE); - assertThat(proj.getFile(projRelativePath), is(file)); - assertThat(folder.getFile(IPath.fromOSString(FILE)), is(file)); - assertThat("file at path '" + file.getFullPath() + "' unexpectedly exists in workspace", - !workspace.getRoot().exists(file.getFullPath())); + assertThat(proj.getFile(projRelativePath)).isEqualTo(file); + assertThat(folder.getFile(IPath.fromOSString(FILE))).isEqualTo(file); + assertThat(file).matches(it -> !workspace.getRoot().exists(it.getFullPath()), "is not contained in workspace"); IPath absolutePath = IPath.fromOSString(proj.getLocation().toOSString() + "/" + FOLDER + "/" + FILE); - assertThat(file.getLocation(), is(absolutePath)); - assertThat(file.getProjectRelativePath(), is(IPath.fromOSString(FOLDER + "/" + FILE))); + assertThat(file.getLocation()).isEqualTo(absolutePath); + assertThat(file.getProjectRelativePath()).isEqualTo(IPath.fromOSString(FOLDER + "/" + FILE)); // Create a folder. folder.create(false, true, monitor); // Parent folder must exist for this. - assertThat(workspace.getRoot().findMember(file.getFullPath()), is(nullValue())); + assertThat(workspace.getRoot().findMember(file.getFullPath())).isNull(); // These tests produce failure because the file does not exist yet. nonexistentFileFailureTests(file, workspace); @@ -121,45 +116,37 @@ public void testFile() throws CoreException { file.create(createInputStream("0123456789"), false, monitor); // Now tests pass that require that the file exists. - assertThat("file does not exist: " + file, file.exists()); - assertThat("no member with name '" + file.getName() + "' exists in folder: " + folder, - folder.findMember(file.getName()).exists()); - assertThat(workspace.getRoot().findMember(file.getFullPath()), is(file)); - assertThat("no member at path '" + file.getFullPath() + "' exists in workspace", - workspace.getRoot().exists(file.getFullPath())); - assertThat(file.getLocation(), is(absolutePath)); + assertThat(file).matches(IFile::exists, "exists") + .matches(it -> workspace.getRoot().exists(it.getFullPath()), "is contained in workspace") + .matches(it -> folder.findMember(it.getName()).exists(), "is contained in folder: " + folder) + .isEqualTo(workspace.getRoot().findMember(file.getFullPath())); + assertThat(file.getLocation()).isEqualTo(absolutePath); /* Session Property */ - assertThat(file.getSessionProperty(Q_NAME_SESSION), is(nullValue())); + assertThat(file.getSessionProperty(Q_NAME_SESSION)).isNull(); file.setSessionProperty(Q_NAME_SESSION, STRING_VALUE); - assertThat(file.getSessionProperty(Q_NAME_SESSION), is(STRING_VALUE)); + assertThat(file.getSessionProperty(Q_NAME_SESSION)).isEqualTo(STRING_VALUE); file.setSessionProperty(Q_NAME_SESSION, null); - assertThat(file.getSessionProperty(Q_NAME_SESSION), is(nullValue())); + assertThat(file.getSessionProperty(Q_NAME_SESSION)).isNull(); // IResource.isLocal(int) // There is no server (yet) so everything should be local. - assertThat("file is not available locally: " + file, isLocal(file, IResource.DEPTH_ZERO)); - // No kids, but it should still answer yes. - assertThat("file and its direct children are not available locally: " + file, - isLocal(file, IResource.DEPTH_ONE)); - assertThat("file and all its children are not available locally: " + file, - isLocal(file, IResource.DEPTH_INFINITE)); + assertThat(file).matches(it -> isLocal(it, IResource.DEPTH_ZERO), "is locally available") + // No kids, but it should still answer yes. + .matches(it -> isLocal(it, IResource.DEPTH_ONE), "is locally available with direct children") + .matches(it -> isLocal(it, IResource.DEPTH_INFINITE), "is locally available with all children"); // These guys have kids. - assertThat("project and all its children are not available locally: " + proj, - isLocal(proj, IResource.DEPTH_INFINITE)); - assertThat("folder and direct children are not available locally: " + folder, - isLocal(folder, IResource.DEPTH_ONE)); - assertThat("folder and all its children are not available locally: " + folder, - isLocal(folder, IResource.DEPTH_INFINITE)); + assertThat(proj).matches(it -> isLocal(it, IResource.DEPTH_ZERO), "is locally available"); + assertThat(folder).matches(it -> isLocal(it, IResource.DEPTH_ONE), "is locally available with direct children") + .matches(it -> isLocal(it, IResource.DEPTH_INFINITE), "is locally available with all children"); // Delete the file file.delete(false, monitor); - assertThat("file exists unexpectedly: " + file, !file.exists()); - assertThat(folder.members(), arrayWithSize(0)); - assertThat(workspace.getRoot().findMember(file.getFullPath()), is(nullValue())); - assertThat("file at path '" + file.getFullPath() + "' unexpectedly exists in workspace", - !workspace.getRoot().exists(file.getFullPath())); - assertThat(file.getLocation(), is(absolutePath)); + assertThat(file).matches(not(IFile::exists), "does not exist") + .matches(it -> !workspace.getRoot().exists(it.getFullPath()), "is not contained in workspace"); + assertThat(folder.members()).isEmpty(); + assertThat(workspace.getRoot().findMember(file.getFullPath())).isNull(); + assertThat(file.getLocation()).isEqualTo(absolutePath); // These tests produce failure because the file no longer exists. nonexistentFileFailureTests(file, workspace); diff --git a/resources/tests/org.eclipse.core.tests.resources/src/org/eclipse/core/tests/resources/usecase/IFolderTest.java b/resources/tests/org.eclipse.core.tests.resources/src/org/eclipse/core/tests/resources/usecase/IFolderTest.java index fa434496e20..0d00c7b7107 100644 --- a/resources/tests/org.eclipse.core.tests.resources/src/org/eclipse/core/tests/resources/usecase/IFolderTest.java +++ b/resources/tests/org.eclipse.core.tests.resources/src/org/eclipse/core/tests/resources/usecase/IFolderTest.java @@ -13,6 +13,8 @@ *******************************************************************************/ package org.eclipse.core.tests.resources.usecase; +import static java.util.function.Predicate.not; +import static org.assertj.core.api.Assertions.assertThat; import static org.eclipse.core.resources.ResourcesPlugin.getWorkspace; import static org.eclipse.core.tests.resources.usecase.IResourceTestUtil.FOLDER; import static org.eclipse.core.tests.resources.usecase.IResourceTestUtil.PROJECT; @@ -20,11 +22,6 @@ import static org.eclipse.core.tests.resources.usecase.IResourceTestUtil.STRING_VALUE; import static org.eclipse.core.tests.resources.usecase.IResourceTestUtil.commonFailureTestsForResource; import static org.eclipse.core.tests.resources.usecase.IResourceTestUtil.isLocal; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.arrayWithSize; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.not; -import static org.hamcrest.Matchers.nullValue; import static org.junit.Assert.assertThrows; import org.eclipse.core.resources.IContainer; @@ -49,17 +46,18 @@ public class IFolderTest { * Get methods either throw an exception or return null (abnormally). * Set methods throw an exception. */ - protected void nonexistentFolderFailureTests(IFolder folder, IContainer parent, IWorkspace wb) throws CoreException { + protected void nonexistentFolderFailureTests(IFolder folder, IContainer parent, IWorkspace workspace) + throws CoreException { /* Tests for failure in get/set methods in IResource. */ commonFailureTestsForResource(folder, false); - assertThat(parent.findMember(folder.getName()), is(nullValue())); + assertThat(parent.findMember(folder.getName())).isNull(); IResource[] members = parent.members(); for (IResource member : members) { - assertThat(member.getName(), not(is(folder.getName()))); + assertThat(member.getName()).isNotEqualTo(folder.getName()); } - assertThat("folder at path '" + folder.getFullPath() + "' unexpectedly exists in workspace", - !wb.getRoot().exists(folder.getFullPath())); + assertThat(folder).matches(it -> !workspace.getRoot().exists(it.getFullPath()), + "is not contained in workspace"); } /** @@ -96,16 +94,16 @@ public void testFolder() throws CoreException { // nonexistent folder // in a nonexistent project. IFolder folder = proj.getFolder(path); - assertThat("folder does not exist: " + folder, !folder.exists()); - assertThat(folder.getWorkspace(), is(workspace)); - assertThat(folder.getProject(), is(proj)); - assertThat(folder.getType(), is(IResource.FOLDER)); - assertThat(folder.getFullPath(), is(IPath.fromOSString("/" + PROJECT + "/" + FOLDER))); - assertThat(folder.getName(), is(FOLDER)); - assertThat(workspace.getRoot().getFolder(folder.getFullPath()), is(folder)); - assertThat(proj.getFolder(path), is(folder)); - assertThat(folder.getParent(), is(proj)); - assertThat(folder.getProjectRelativePath(), is(IPath.fromOSString(FOLDER))); + assertThat(folder).matches(not(IFolder::exists), "does not exist"); + assertThat(folder.getWorkspace()).isEqualTo(workspace); + assertThat(folder.getProject()).isEqualTo(proj); + assertThat(folder.getType()).isEqualTo(IResource.FOLDER); + assertThat(folder.getFullPath()).isEqualTo(IPath.fromOSString("/" + PROJECT + "/" + FOLDER)); + assertThat(folder.getName()).isEqualTo(FOLDER); + assertThat(workspace.getRoot().getFolder(folder.getFullPath())).isEqualTo(folder); + assertThat(proj.getFolder(path)).isEqualTo(folder); + assertThat(folder.getParent()).isEqualTo(proj); + assertThat(folder.getProjectRelativePath()).isEqualTo(IPath.fromOSString(FOLDER)); // Create a project without opening it. proj.create(monitor); @@ -119,62 +117,56 @@ public void testFolder() throws CoreException { // These tests produce failure because the folder does not exist yet. nonexistentFolderFailureTests(folder, proj, workspace); IPath absolutePath = IPath.fromOSString(proj.getLocation().toOSString() + "/" + FOLDER); - assertThat(folder.getLocation(), is(absolutePath)); + assertThat(folder.getLocation()).isEqualTo(absolutePath); // Now create folder. folder.create(false, true, monitor); // The tests that failed above (becaues the folder must exist) now pass. - assertThat("folder does not exist: " + folder, folder.exists()); - assertThat("no member exists at path '" + folder.getFullPath() + "' in workspace", - workspace.getRoot().findMember(folder.getFullPath()).exists()); - assertThat(workspace.getRoot().findMember(folder.getFullPath()), is(folder)); - assertThat("folder at path '" + folder.getFullPath() + "' does not exist in workspace", - workspace.getRoot().exists(folder.getFullPath())); - assertThat(folder.getLocation(), is(absolutePath)); + assertThat(folder).matches(IFolder::exists, "exists") + .matches(it -> workspace.getRoot().exists(it.getFullPath()), "is contained in workspace") + .matches(it -> workspace.getRoot().findMember(it.getFullPath()).exists(), + "is found existing in workspace") + .isEqualTo(workspace.getRoot().findMember(folder.getFullPath())); + assertThat(folder.getLocation()).isEqualTo(absolutePath); // Session Property - assertThat(folder.getSessionProperty(Q_NAME_SESSION), is(nullValue())); + assertThat(folder.getSessionProperty(Q_NAME_SESSION)).isNull(); folder.setSessionProperty(Q_NAME_SESSION, STRING_VALUE); - assertThat(folder.getSessionProperty(Q_NAME_SESSION), is(STRING_VALUE)); + assertThat(folder.getSessionProperty(Q_NAME_SESSION)).isEqualTo(STRING_VALUE); folder.setSessionProperty(Q_NAME_SESSION, null); - assertThat(folder.getSessionProperty(Q_NAME_SESSION), is(nullValue())); + assertThat(folder.getSessionProperty(Q_NAME_SESSION)).isNull(); // IResource.isLocal(int) // There is no server (yet) so everything should be local. - assertThat("folder is not available locally: " + folder, isLocal(folder, IResource.DEPTH_ZERO)); - // No kids, but it should still answer yes. - assertThat("folder and its direct children are not available locally: " + folder, - isLocal(folder, IResource.DEPTH_ONE)); - assertThat("folder and all its children are not available locally: " + folder, - isLocal(folder, IResource.DEPTH_INFINITE)); + assertThat(folder).matches(it -> isLocal(it, IResource.DEPTH_ZERO), "is locally available") + // No kids, but it should still answer yes. + .matches(it -> isLocal(it, IResource.DEPTH_ONE), "is locally available with direct children") + .matches(it -> isLocal(it, IResource.DEPTH_INFINITE), "is locally available with all children"); // These guys have kids. - assertThat("project and direct children are not available locally: " + proj, - isLocal(proj, IResource.DEPTH_ONE)); - assertThat("project and all its children are not available locally: " + proj, - isLocal(proj, IResource.DEPTH_INFINITE)); + assertThat(proj).matches(it -> isLocal(it, IResource.DEPTH_ONE), "is locally available with direct children") + .matches(it -> isLocal(it, IResource.DEPTH_INFINITE), "is locally available with all children"); // Construct a nested folder handle. IFolder nestedFolder = getWorkspace().getRoot().getFolder(folder.getFullPath().append(FOLDER)); // Inspection methods with meaningful results invoked on a handle for a // nonexistent folder. - assertThat("nested folder exists unexpectedly: " + nestedFolder, !nestedFolder.exists()); - assertThat(nestedFolder.getWorkspace(), is(workspace)); - assertThat(nestedFolder.getProject(), is(proj)); - assertThat(nestedFolder.getType(), is(IResource.FOLDER)); - assertThat(nestedFolder.getFullPath(), is(IPath.fromOSString("/" + PROJECT + "/" + FOLDER + "/" + FOLDER))); - assertThat(nestedFolder.getName(), is(FOLDER)); - assertThat(workspace.getRoot().getFolder(nestedFolder.getFullPath()), is(nestedFolder)); + assertThat(nestedFolder).matches(not(IFolder::exists), "does not exist"); + assertThat(nestedFolder.getWorkspace()).isEqualTo(workspace); + assertThat(nestedFolder.getProject()).isEqualTo(proj); + assertThat(nestedFolder.getType()).isEqualTo(IResource.FOLDER); + assertThat(nestedFolder.getFullPath()) + .isEqualTo(IPath.fromOSString("/" + PROJECT + "/" + FOLDER + "/" + FOLDER)); + assertThat(nestedFolder.getName()).isEqualTo(FOLDER); + assertThat(workspace.getRoot().getFolder(nestedFolder.getFullPath())).isEqualTo(nestedFolder); IPath projRelativePath = IPath.fromOSString(FOLDER + "/" + FOLDER); - assertThat(proj.getFolder(projRelativePath), is(nestedFolder)); - assertThat(nestedFolder.getParent(), is(folder)); - assertThat(nestedFolder.getProjectRelativePath(), is(IPath.fromOSString(FOLDER + "/" + FOLDER))); + assertThat(proj.getFolder(projRelativePath)).isEqualTo(nestedFolder); + assertThat(nestedFolder.getParent()).isEqualTo(folder); + assertThat(nestedFolder.getProjectRelativePath()).isEqualTo(IPath.fromOSString(FOLDER + "/" + FOLDER)); // Now the parent folder has a kid. - assertThat("folder and its direct children are not available locally: " + folder, - isLocal(folder, IResource.DEPTH_ONE)); - assertThat("folder and all its children are not available locally: " + folder, - isLocal(folder, IResource.DEPTH_INFINITE)); + assertThat(folder).matches(it -> isLocal(it, IResource.DEPTH_ONE), "is locally available with direct children") + .matches(it -> isLocal(it, IResource.DEPTH_INFINITE), "is locally available with all children"); // These tests produce failure because the nested folder does not exist yet. nonexistentFolderFailureTests(nestedFolder, folder, workspace); @@ -182,45 +174,41 @@ public void testFolder() throws CoreException { // Create the nested folder. nestedFolder.create(false, true, monitor); - // The tests that failed above (becaues the folder must exist) now pass. - assertThat("nested folder at path '" + nestedFolder.getFullPath() + "' does not exist in workspace", - workspace.getRoot().exists(nestedFolder.getFullPath())); - assertThat("nested folder does not exist: " + nestedFolder, nestedFolder.exists()); - assertThat("no folder with name '" + nestedFolder.getName() + "' exists in folder: " + folder, - folder.findMember(nestedFolder.getName()).exists()); - assertThat(workspace.getRoot().findMember(nestedFolder.getFullPath()), is(nestedFolder)); - assertThat("no nested folder at path '" + nestedFolder.getFullPath() + "' exists in workspace", - workspace.getRoot().exists(nestedFolder.getFullPath())); - assertThat(nestedFolder.getLocation(), is(absolutePath.append(FOLDER))); + // The tests that failed above (becauese the folder must exist) now pass. + assertThat(nestedFolder).matches(IFolder::exists, "exists") + .matches(it -> folder.findMember(it.getName()).exists(), "is contained in folder: " + folder) + .matches(it -> workspace.getRoot().exists(it.getFullPath()), "is contained in workspace") + .matches(it -> workspace.getRoot().findMember(it.getFullPath()).exists(), + "is found existing in workspace") + .isEqualTo(workspace.getRoot().findMember(nestedFolder.getFullPath())); + assertThat(nestedFolder.getLocation()).isEqualTo(absolutePath.append(FOLDER)); // Delete the nested folder nestedFolder.delete(false, monitor); - assertThat("nested folder exists unexpectedly: " + nestedFolder, !nestedFolder.exists()); - assertThat(folder.members(), arrayWithSize(0)); - assertThat(workspace.getRoot().findMember(nestedFolder.getFullPath()), is(nullValue())); - assertThat("nested folder at path '" + nestedFolder.getFullPath() + "' unexpectedly exists in workspace", - !workspace.getRoot().exists(nestedFolder.getFullPath())); - assertThat(nestedFolder.getLocation(), is(absolutePath.append(FOLDER))); + assertThat(nestedFolder).matches(not(IFolder::exists), "does not exist"); + assertThat(folder.members()).isEmpty(); + assertThat(workspace.getRoot().findMember(nestedFolder.getFullPath())).isNull(); + assertThat(nestedFolder).matches(it -> !workspace.getRoot().exists(it.getFullPath()), + "is not contained in workspace"); + assertThat(nestedFolder.getLocation()).isEqualTo(absolutePath.append(FOLDER)); // These tests produce failure because the nested folder no longer exists. nonexistentFolderFailureTests(nestedFolder, folder, workspace); // Parent is still there. - assertThat("folder does not exist: " + folder, folder.exists()); - assertThat("no member at path '" + folder.getFullPath() + "' exists in workspace", - workspace.getRoot().findMember(folder.getFullPath()).exists()); - assertThat(workspace.getRoot().findMember(folder.getFullPath()), is(folder)); - assertThat("no folder at path '" + folder.getFullPath() + "' exists in workspace", - workspace.getRoot().exists(folder.getFullPath())); - assertThat(folder.getLocation(), is(absolutePath)); + assertThat(folder).matches(IFolder::exists, "exists") + .matches(it -> workspace.getRoot().exists(it.getFullPath()), "is contained in workspace") + .matches(it -> workspace.getRoot().findMember(it.getFullPath()).exists(), + "is found existing in workspace") + .isEqualTo(workspace.getRoot().findMember(folder.getFullPath())); + assertThat(folder.getLocation()).isEqualTo(absolutePath); // Delete the parent folder folder.delete(false, monitor); - assertThat("folder exists unexpectedly: " + folder, !folder.exists()); - assertThat(workspace.getRoot().findMember(folder.getFullPath()), is(nullValue())); - assertThat("folder at path '" + folder.getFullPath() + "' unexpectedly exists in workspace", - !workspace.getRoot().exists(folder.getFullPath())); - assertThat(folder.getLocation(), is(absolutePath)); + assertThat(folder).matches(not(IFolder::exists), "does not exist") + .matches(it -> !workspace.getRoot().exists(it.getFullPath()), "is not contained in workspace"); + assertThat(workspace.getRoot().findMember(folder.getFullPath())).isNull(); + assertThat(folder.getLocation()).isEqualTo(absolutePath); // These tests produce failure because the parent folder no longer exists. nonexistentFolderFailureTests(folder, proj, workspace); @@ -231,11 +219,11 @@ public void testFolder() throws CoreException { * Get methods either throw an exception or return null (abnormally). * Set methods throw an exception. */ - protected void unopenedProjectFailureTests(IFolder folder, IContainer parent, IWorkspace wb) { + protected void unopenedProjectFailureTests(IFolder folder, IContainer parent, IWorkspace workspace) { /* Try creating a folder in a project which is not yet open. */ assertThrows(CoreException.class, () -> folder.create(false, true, null)); - assertThat("folder at path '" + folder.getFullPath() + "' unexpectedly exists in workspace", - !wb.getRoot().exists(folder.getFullPath())); + assertThat(folder).matches(it -> !workspace.getRoot().exists(it.getFullPath()), + "is not contained in workspace"); } } diff --git a/resources/tests/org.eclipse.core.tests.resources/src/org/eclipse/core/tests/resources/usecase/IProjectTest.java b/resources/tests/org.eclipse.core.tests.resources/src/org/eclipse/core/tests/resources/usecase/IProjectTest.java index 0ae90aac5e6..64ae7862622 100644 --- a/resources/tests/org.eclipse.core.tests.resources/src/org/eclipse/core/tests/resources/usecase/IProjectTest.java +++ b/resources/tests/org.eclipse.core.tests.resources/src/org/eclipse/core/tests/resources/usecase/IProjectTest.java @@ -14,19 +14,15 @@ *******************************************************************************/ package org.eclipse.core.tests.resources.usecase; +import static java.util.function.Predicate.not; +import static org.assertj.core.api.Assertions.assertThat; import static org.eclipse.core.resources.ResourcesPlugin.getWorkspace; import static org.eclipse.core.tests.resources.usecase.IResourceTestUtil.PROJECT; import static org.eclipse.core.tests.resources.usecase.IResourceTestUtil.Q_NAME_SESSION; import static org.eclipse.core.tests.resources.usecase.IResourceTestUtil.STRING_VALUE; import static org.eclipse.core.tests.resources.usecase.IResourceTestUtil.commonFailureTestsForResource; import static org.eclipse.core.tests.resources.usecase.IResourceTestUtil.isLocal; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.arrayWithSize; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.not; -import static org.hamcrest.Matchers.nullValue; import static org.junit.Assert.assertThrows; -import static org.junit.Assert.assertTrue; import java.util.Hashtable; import org.eclipse.core.resources.ICommand; @@ -79,13 +75,13 @@ protected void nonexistentProjectFailureTests(IProject proj) { // Try to open a non-created project. assertThrows(CoreException.class, () -> proj.open(monitor)); - assertThat("project is unexpectedly open: " + proj, !proj.isOpen()); + assertThat(proj).matches(not(IProject::isOpen), "is not open"); // addMapping assertThrows(Exception.class, () -> proj.getDescription().setLocation(IPath.fromOSString(LOCAL_LOCATION_PATH_STRING_0))); - assertThat(wb.getRoot().getProjects(), arrayWithSize(0)); + assertThat(wb.getRoot().getProjects()).isEmpty(); } /** @@ -115,28 +111,27 @@ protected void nonexistentProjectFailureTests(IProject proj) { */ @Test public void testProject() throws CoreException { - IWorkspace wb = getWorkspace(); + IWorkspace workspace = getWorkspace(); IProgressMonitor monitor = null; // Create a project handle. - IProject proj = wb.getRoot().getProject(PROJECT); + IProject proj = workspace.getRoot().getProject(PROJECT); // Inspection methods with meaningful results invoked on a handle for a nonexistent project - assertThat("project exists unexpectedly: " + proj, !proj.exists()); - assertThat(proj.getWorkspace(), is(wb)); - assertThat(proj.getType(), is(IResource.PROJECT)); - assertThat(proj.getFullPath(), is(IPath.fromOSString("/" + PROJECT))); - assertThat(proj.getName(), is(PROJECT)); - assertThat("project at path '" + proj.getFullPath() + "' unexpectedly exists in workspace", - !wb.getRoot().exists(proj.getFullPath())); - assertThat(wb.getRoot().findMember(proj.getFullPath()), is(nullValue())); - assertThat(proj.getParent(), is(wb.getRoot())); + assertThat(proj).matches(not(IProject::exists), "does not exist"); + assertThat(proj.getWorkspace()).isEqualTo(workspace); + assertThat(proj.getType()).isEqualTo(IResource.PROJECT); + assertThat(proj.getFullPath()).isEqualTo(IPath.fromOSString("/" + PROJECT)); + assertThat(proj.getName()).isEqualTo(PROJECT); + assertThat(proj).matches(it -> !workspace.getRoot().exists(it.getFullPath()), "is not contained in workspace"); + assertThat(workspace.getRoot().findMember(proj.getFullPath())).isNull(); + assertThat(proj.getParent()).isEqualTo(workspace.getRoot()); // Legal question inherited from IResource: returns the receiver. - assertThat(proj.getProject(), is(proj)); - assertThat(proj.getProjectRelativePath(), is(IPath.fromOSString(""))); + assertThat(proj.getProject()).isEqualTo(proj); + assertThat(proj.getProjectRelativePath()).isEqualTo(IPath.fromOSString("")); // Check that there are no projects. - assertThat(wb.getRoot().getProjects(), arrayWithSize(0)); + assertThat(workspace.getRoot().getProjects()).isEmpty(); // These tests produce failure because the project does not exist yet. nonexistentProjectFailureTests(proj); @@ -144,37 +139,35 @@ public void testProject() throws CoreException { // Create the project. proj.create(monitor); - // Check that the project is get-able from the containers. - assertThat("project does not exist: " + proj, proj.exists()); - assertThat("project with name '" + proj.getName() + "' does not exist in workspace", - wb.getRoot().findMember(proj.getName()).exists()); - assertTrue("project at path '" + proj.getFullPath() + "' does not exist in workspace", - wb.getRoot().exists(proj.getFullPath())); - // But it is still not open. - assertThat("project is unexpectedly open: " + proj, !proj.isOpen()); - assertThat(wb.getRoot().findMember(proj.getFullPath()), is(proj)); + // Check that the project is get-able from the containers but still not open + assertThat(proj).matches(IProject::exists, "exists") + .matches(it -> workspace.getRoot().exists(it.getFullPath()), "is contained in workspace") + .matches(it -> workspace.getRoot().findMember(it.getFullPath()).exists(), + "is found existing in workspace") + .isEqualTo(workspace.getRoot().findMember(proj.getFullPath())) + .matches(not(IProject::isOpen), "is open"); // These tests produce failure because the project has not been opened yet. unopenedProjectFailureTests(proj); // Open project proj.open(monitor); - assertThat("project is not open: " + proj, proj.isOpen()); - assertThat(proj.getLocation(), not(is(nullValue()))); + assertThat(proj).matches(IProject::isOpen, "is open"); + assertThat(proj.getLocation()).isNotNull(); /* Properties */ // Session Property - assertThat(proj.getSessionProperty(Q_NAME_SESSION), is(nullValue())); + assertThat(proj.getSessionProperty(Q_NAME_SESSION)).isNull(); proj.setSessionProperty(Q_NAME_SESSION, STRING_VALUE); - assertThat(proj.getSessionProperty(Q_NAME_SESSION), is(STRING_VALUE)); + assertThat(proj.getSessionProperty(Q_NAME_SESSION)).isEqualTo(STRING_VALUE); proj.setSessionProperty(Q_NAME_SESSION, null); - assertThat(proj.getSessionProperty(Q_NAME_SESSION), is(nullValue())); + assertThat(proj.getSessionProperty(Q_NAME_SESSION)).isNull(); // Project buildspec IProjectDescription desc = proj.getDescription(); - assertThat(desc.getBuildSpec(), arrayWithSize(0)); + assertThat(desc.getBuildSpec()).isEmpty(); ICommand command = desc.newCommand(); command.setBuilderName("org.eclipse.core.tests.buildername"); ICommand[] commands = new ICommand[] {command}; @@ -185,25 +178,21 @@ public void testProject() throws CoreException { desc.setBuildSpec(commands); // Compare project buildspecs - assertThat(commands, is(desc.getBuildSpec())); + assertThat(commands).isEqualTo(desc.getBuildSpec()); // IResource.isLocal(int) - assertThat("project is not available locally: " + proj, isLocal(proj, IResource.DEPTH_ZERO)); - // No kids, but it should still answer yes. - assertThat("project and its direct children are not available locally: " + proj, - isLocal(proj, IResource.DEPTH_ONE)); - assertThat("project and all its children are not available locally: " + proj, - isLocal(proj, IResource.DEPTH_INFINITE)); + assertThat(proj).matches(it -> isLocal(it, IResource.DEPTH_ZERO), "is locally available") + // No kids, but it should still answer yes. + .matches(it -> isLocal(it, IResource.DEPTH_ONE), "is locally available with direct children") + .matches(it -> isLocal(it, IResource.DEPTH_INFINITE), "is locally available with all children"); // Close project proj.close(monitor); - // The project is no longer open - assertThat("project has not been closed: " + proj, !proj.isOpen()); - // But it still exists. - assertThat("project does not exist: " + proj, proj.exists()); - assertThat(wb.getRoot().findMember(proj.getFullPath()), is(proj)); - assertTrue("project at path '" + proj.getFullPath() + "' does not exist in workspace", - wb.getRoot().exists(proj.getFullPath())); + // The project is no longer open but still exists + assertThat(proj).matches(not(IProject::isOpen), "is not open") // + .matches(IProject::exists, "exists") + .matches(it -> workspace.getRoot().exists(it.getFullPath()), "is contained in workspace") + .isEqualTo(workspace.getRoot().findMember(proj.getFullPath())); // These tests produce failure because the project is now closed. unopenedProjectFailureTests(proj); @@ -212,13 +201,12 @@ public void testProject() throws CoreException { proj.delete(true, true, monitor); // The project no longer exists. - assertThat("project unexpectedly exists: " + proj, !proj.exists()); - assertThat(wb.getRoot().getProjects(), arrayWithSize(0)); - assertThat(wb.getRoot().findMember(proj.getFullPath()), is(nullValue())); + assertThat(proj).matches(not(IProject::exists), "does not exist"); + assertThat(workspace.getRoot().getProjects()).isEmpty(); + assertThat(workspace.getRoot().findMember(proj.getFullPath())).isNull(); // These tests produce failure because the project no longer exists. nonexistentProjectFailureTests(proj); - assertTrue("project at path '" + proj.getFullPath() + "' unexpectedly exists in workspace", - !wb.getRoot().exists(proj.getFullPath())); + assertThat(proj).matches(it -> !workspace.getRoot().exists(it.getFullPath()), "is not contained in workspace"); } /** @@ -230,12 +218,11 @@ protected void unopenedProjectFailureTests(IProject proj) { commonFailureTests(proj, true); } - protected void unopenedSolutionFailureTests(IProject proj, IWorkspace wb) { + protected void unopenedSolutionFailureTests(IProject proj, IWorkspace workspace) { // Try to create the project without the solution being open. assertThrows(CoreException.class, () -> proj.create(null)); - assertThat("project unexpectedly exists: " + proj, !proj.exists()); - assertTrue("project at path '" + proj.getFullPath() + "' unexpectedly exists in workspace", - wb.getRoot().exists(proj.getFullPath())); + assertThat(proj).matches(not(IProject::exists), "does not exist"); + assertThat(proj).matches(it -> workspace.getRoot().exists(it.getFullPath()), "is contained in workspace"); } } diff --git a/runtime/tests/org.eclipse.core.tests.harness/META-INF/MANIFEST.MF b/runtime/tests/org.eclipse.core.tests.harness/META-INF/MANIFEST.MF index 0af68b3d091..90638e7726c 100644 --- a/runtime/tests/org.eclipse.core.tests.harness/META-INF/MANIFEST.MF +++ b/runtime/tests/org.eclipse.core.tests.harness/META-INF/MANIFEST.MF @@ -15,7 +15,9 @@ Require-Bundle: org.junit, Bundle-ActivationPolicy: lazy Bundle-RequiredExecutionEnvironment: JavaSE-17 Import-Package: javax.xml.parsers, + net.bytebuddy, org.apiguardian.api, + org.assertj.core.api, org.junit.jupiter.api, org.junit.platform.suite.api, org.junit.platform.commons, diff --git a/runtime/tests/org.eclipse.core.tests.harness/src/org/eclipse/core/tests/harness/FussyProgressMonitor.java b/runtime/tests/org.eclipse.core.tests.harness/src/org/eclipse/core/tests/harness/FussyProgressMonitor.java index 26372a7c19d..0eed39172f5 100644 --- a/runtime/tests/org.eclipse.core.tests.harness/src/org/eclipse/core/tests/harness/FussyProgressMonitor.java +++ b/runtime/tests/org.eclipse.core.tests.harness/src/org/eclipse/core/tests/harness/FussyProgressMonitor.java @@ -13,16 +13,10 @@ *******************************************************************************/ package org.eclipse.core.tests.harness; -import static org.hamcrest.Matchers.anyOf; -import static org.hamcrest.Matchers.greaterThan; -import static org.hamcrest.Matchers.greaterThanOrEqualTo; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.lessThanOrEqualTo; +import static org.assertj.core.api.Assertions.assertThat; import junit.framework.AssertionFailedError; import org.eclipse.core.runtime.jobs.Job; -import org.hamcrest.Matcher; -import org.hamcrest.MatcherAssert; /** * This class can be used for testing progress monitoring. @@ -68,25 +62,13 @@ public FussyProgressMonitor(Job job) { this.job = job; } - private void assertThat(String reason, T actual, Matcher matcher) { + private void wrapAssertion(Runnable assertion) { // silently ignore follow-up failures if (hasFailed) { return; } try { - MatcherAssert.assertThat(reason, actual, matcher); - } catch (AssertionError error) { - processFailedAssertion(error); - } - } - - private void assertThat(String reason, boolean condition) { - // silently ignore follow-up failures - if (hasFailed) { - return; - } - try { - MatcherAssert.assertThat(reason, condition); + assertion.run(); } catch (AssertionError error) { processFailedAssertion(error); } @@ -108,16 +90,20 @@ public void processFailedAssertion(AssertionError assertionError) throws FussyPr * Asserts that this progress monitor is all used up */ public void assertUsedUp() { - assertThat("beginTask has not been called on ProgressMonitor", beginTaskCalled); - assertThat("ProgressMonitor not used up", Math.round(workedSoFar), greaterThanOrEqualTo((long) totalWork)); + wrapAssertion( + () -> assertThat(beginTaskCalled).withFailMessage("beginTask has not been called on ProgressMonitor") + .isTrue()); + wrapAssertion(() -> assertThat(Math.round(workedSoFar)).as("work done").isGreaterThanOrEqualTo(totalWork)); } @Override public void beginTask(String name, int newTotalWork) { - assertThat("beginTask may only be called once (old name=" + taskName + ")", !beginTaskCalled); + wrapAssertion(() -> assertThat(beginTaskCalled) + .withFailMessage("beginTask may only be called once (old name=%s)", taskName).isFalse()); beginTaskCalled = true; taskName = name; - assertThat("total work must be positive or UNKNOWN", newTotalWork, anyOf(is(UNKNOWN), greaterThan(0))); + wrapAssertion(() -> assertThat(newTotalWork).as("total work").satisfiesAnyOf( + work -> assertThat(work).isEqualTo(UNKNOWN), work -> assertThat(work).isGreaterThan(0))); this.totalWork = newTotalWork; beginTime = System.currentTimeMillis(); } @@ -130,13 +116,15 @@ public void done() { @Override public void internalWorked(double work) { - assertThat("can accept calls to worked/internalWorked only after beginTask", beginTaskCalled); - assertThat("can accept calls to worked/internalWorked only before done is called", doneCalls, is(0)); - assertThat("amount worked should be positive", work, greaterThan(0.0)); + wrapAssertion(() -> assertThat(beginTaskCalled) + .withFailMessage("can accept calls to worked/internalWorked only after beginTask").isTrue()); + wrapAssertion(() -> assertThat(doneCalls) + .withFailMessage("can accept calls to worked/internalWorked only before done is called").isZero()); + wrapAssertion(() -> assertThat(work).as("amount worked").isGreaterThan(0.0)); workedSoFar += work; if (totalWork != UNKNOWN) { - assertThat("worked more than totalWork", workedSoFar, - lessThanOrEqualTo(totalWork + (totalWork * EPS_FACTOR))); + wrapAssertion(() -> assertThat(workedSoFar).as("total work done") + .isLessThanOrEqualTo(totalWork + (totalWork * EPS_FACTOR))); } } @@ -162,12 +150,14 @@ public void prepare() { * should be called after every use of a FussyProgressMonitor */ public void sanityCheck() { - assertThat("sanityCheck has already been called", !sanityCheckCalled); + wrapAssertion( + () -> assertThat(sanityCheckCalled).withFailMessage("sanityCheck has already been called").isFalse()); sanityCheckCalled = true; long duration = System.currentTimeMillis() - beginTime; if (duration > NOTICEABLE_DELAY && beginTaskCalled) { - assertThat("this operation took: " + duration + "ms, it should report progress", workedSoFar, - greaterThan(0.0)); + wrapAssertion(() -> assertThat(workedSoFar) + .withFailMessage("this operation took: %s ms, it should report progress", duration) + .isGreaterThan(0.0)); } } diff --git a/runtime/tests/org.eclipse.core.tests.harness/src/org/eclipse/core/tests/session/ConfigurationSessionTestSuite.java b/runtime/tests/org.eclipse.core.tests.harness/src/org/eclipse/core/tests/session/ConfigurationSessionTestSuite.java index d34767cea2b..1f1ab78844a 100644 --- a/runtime/tests/org.eclipse.core.tests.harness/src/org/eclipse/core/tests/session/ConfigurationSessionTestSuite.java +++ b/runtime/tests/org.eclipse.core.tests.harness/src/org/eclipse/core/tests/session/ConfigurationSessionTestSuite.java @@ -93,6 +93,8 @@ public void addMinimalBundleSet() { addBundle(org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader.class); // org.eclipse.jdt.junit4.runtime addBundle(org.eclipse.pde.internal.junit.runtime.CoreTestApplication.class); // org.eclipse.pde.junit.runtime + addBundle(net.bytebuddy.ByteBuddy.class); // net.bytebuddy for org.assertj.core.api + addBundle(org.assertj.core.api.Assertions.class); // org.assertj.core.api addBundle(org.hamcrest.CoreMatchers.class); // org.hamcrest.core // The org.junit bundle requires an org.hamcrest.core bundle, but as of version diff --git a/runtime/tests/org.eclipse.core.tests.runtime/META-INF/MANIFEST.MF b/runtime/tests/org.eclipse.core.tests.runtime/META-INF/MANIFEST.MF index 911a55d4cf4..e3c5bef1f60 100644 --- a/runtime/tests/org.eclipse.core.tests.runtime/META-INF/MANIFEST.MF +++ b/runtime/tests/org.eclipse.core.tests.runtime/META-INF/MANIFEST.MF @@ -14,6 +14,7 @@ Require-Bundle: org.junit, org.eclipse.test.performance;resolution:=optional, org.eclipse.core.runtime;bundle-version="3.29.0", org.eclipse.core.tests.harness;bundle-version="3.11.0" +Import-Package: org.assertj.core.api Bundle-ActivationPolicy: lazy Bundle-RequiredExecutionEnvironment: JavaSE-17 Plugin-Class: org.eclipse.core.tests.runtime.RuntimeTestsPlugin diff --git a/runtime/tests/org.eclipse.core.tests.runtime/src/org/eclipse/core/tests/internal/preferences/EclipsePreferencesTest.java b/runtime/tests/org.eclipse.core.tests.runtime/src/org/eclipse/core/tests/internal/preferences/EclipsePreferencesTest.java index a135412121d..1b4d360ecde 100644 --- a/runtime/tests/org.eclipse.core.tests.runtime/src/org/eclipse/core/tests/internal/preferences/EclipsePreferencesTest.java +++ b/runtime/tests/org.eclipse.core.tests.runtime/src/org/eclipse/core/tests/internal/preferences/EclipsePreferencesTest.java @@ -13,9 +13,7 @@ *******************************************************************************/ package org.eclipse.core.tests.internal.preferences; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.collection.ArrayMatching.arrayContainingInAnyOrder; -import static org.hamcrest.collection.IsIterableContainingInAnyOrder.containsInAnyOrder; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; @@ -606,7 +604,7 @@ public void testKeys() throws BackingStoreException { // get the key list String[] result = node.keys(); - assertThat(keys, arrayContainingInAnyOrder(result)); + assertThat(keys).containsExactlyInAnyOrder(result); } @Test @@ -624,7 +622,7 @@ public void testChildrenNames() throws BackingStoreException { node.node(childrenName); } result = node.childrenNames(); - assertThat(childrenNames, arrayContainingInAnyOrder(result)); + assertThat(childrenNames).containsExactlyInAnyOrder(result); } @Test @@ -690,7 +688,7 @@ public void testClear() throws BackingStoreException { node.put(keys[i], values[i]); } assertEquals("2.0", keys.length, node.keys().length); - assertThat(keys, arrayContainingInAnyOrder(node.keys())); + assertThat(keys).containsExactlyInAnyOrder(node.keys()); // clear the values and check node.clear(); @@ -726,18 +724,15 @@ public void testAccept() throws BackingStoreException { ArrayList expected = new ArrayList<>(); final ArrayList actual = new ArrayList<>(); - IPreferenceNodeVisitor visitor = new IPreferenceNodeVisitor() { - @Override - public boolean visit(IEclipsePreferences node) { - actual.add(node.absolutePath()); - return true; - } + IPreferenceNodeVisitor visitor = node -> { + actual.add(node.absolutePath()); + return true; }; // just the scope root scopeRoot.accept(visitor); expected.add(scopeRoot.absolutePath()); - assertThat(actual, containsInAnyOrder(expected.toArray(new String[0]))); + assertThat(actual).containsExactlyInAnyOrderElementsOf(actual); Set children = new HashSet<>(); children.add(getUniqueString()); @@ -753,7 +748,7 @@ public boolean visit(IEclipsePreferences node) { scopeRoot.node(s); } scopeRoot.accept(visitor); - assertThat(actual, containsInAnyOrder(expected.toArray(new String[0]))); + assertThat(actual).containsExactlyInAnyOrderElementsOf(expected); } @Test diff --git a/runtime/tests/org.eclipse.core.tests.runtime/src/org/eclipse/core/tests/runtime/XmlProcessorFactoryTest.java b/runtime/tests/org.eclipse.core.tests.runtime/src/org/eclipse/core/tests/runtime/XmlProcessorFactoryTest.java index b09d93fed81..a1c8b442dbb 100644 --- a/runtime/tests/org.eclipse.core.tests.runtime/src/org/eclipse/core/tests/runtime/XmlProcessorFactoryTest.java +++ b/runtime/tests/org.eclipse.core.tests.runtime/src/org/eclipse/core/tests/runtime/XmlProcessorFactoryTest.java @@ -10,10 +10,7 @@ *******************************************************************************/ package org.eclipse.core.tests.runtime; -import static org.hamcrest.CoreMatchers.containsString; -import static org.hamcrest.CoreMatchers.not; -import static org.hamcrest.CoreMatchers.startsWith; -import static org.hamcrest.MatcherAssert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; @@ -352,8 +349,8 @@ public void run() { try (OutputStream outputStream = socket.getOutputStream()) { outputStream.write("HTTP/1.1 200 OK\r\n".getBytes(StandardCharsets.UTF_8)); } - assertThat(firstLine, startsWith("GET")); - assertThat(firstLine, not(containsString("secret"))); + assertThat(firstLine).startsWith("GET"); + assertThat(firstLine).doesNotContain("secret"); fail("Server was contacted"); } } catch (SocketException closed) { diff --git a/runtime/tests/org.eclipse.core.tests.runtime/src/org/eclipse/core/tests/runtime/jobs/BeginEndRuleTest.java b/runtime/tests/org.eclipse.core.tests.runtime/src/org/eclipse/core/tests/runtime/jobs/BeginEndRuleTest.java index 02ef40ac64d..5e5d75523eb 100644 --- a/runtime/tests/org.eclipse.core.tests.runtime/src/org/eclipse/core/tests/runtime/jobs/BeginEndRuleTest.java +++ b/runtime/tests/org.eclipse.core.tests.runtime/src/org/eclipse/core/tests/runtime/jobs/BeginEndRuleTest.java @@ -13,10 +13,7 @@ *******************************************************************************/ package org.eclipse.core.tests.runtime.jobs; -import static org.hamcrest.CoreMatchers.hasItem; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.CoreMatchers.not; -import static org.hamcrest.MatcherAssert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertThrows; @@ -603,9 +600,8 @@ public void running(IJobChangeEvent event) { } rescheduledJob.join(TIMEOUT_IN_MILLIS, new NullProgressMonitor()); Job.getJobManager().removeJobChangeListener(runningThreadStoreListener); - assertThat("ThreadJob did not finish", rescheduledJob.getState(), is(Job.NONE)); - assertThat("ThreadJob did not ignore reschedule", jobsStartedRunning, - not(hasItem(rescheduledJob))); + assertThat(rescheduledJob.getState()).as("state of job expected to be finished").isEqualTo(Job.NONE); + assertThat(jobsStartedRunning).as("started jobs").doesNotContain(rescheduledJob); } @Test @@ -628,8 +624,8 @@ public void running(IJobChangeEvent event) { } scheduledJob.join(TIMEOUT_IN_MILLIS, new NullProgressMonitor()); Job.getJobManager().removeJobChangeListener(runningThreadStoreListener); - assertThat("ThreadJob did not finish", scheduledJob.getState(), is(Job.NONE)); - assertThat("ThreadJob was rescheduled", jobsStartedRunning, not(hasItem(scheduledJob))); + assertThat(scheduledJob.getState()).as("state of job expected to be finished").isEqualTo(Job.NONE); + assertThat(jobsStartedRunning).as("started jobs").doesNotContain(scheduledJob); } @Test @@ -667,8 +663,8 @@ protected IStatus run(IProgressMonitor monitor) { job.join(TIMEOUT_IN_MILLIS, new NullProgressMonitor()); scheduledJob.get().join(TIMEOUT_IN_MILLIS, new NullProgressMonitor()); Job.getJobManager().removeJobChangeListener(runningThreadStoreListener); - assertThat("Another nested job was created", job, is(scheduledJob.get())); - assertThat("Job did not finish", job.getState(), is(Job.NONE)); + assertThat(scheduledJob.get()).as("job in nested rule expected to be same as outer job").isEqualTo(job); + assertThat(job.getState()).as("state of job expected to be finished").isEqualTo(Job.NONE); } } diff --git a/runtime/tests/org.eclipse.core.tests.runtime/src/org/eclipse/core/tests/runtime/jobs/IJobManagerTest.java b/runtime/tests/org.eclipse.core.tests.runtime/src/org/eclipse/core/tests/runtime/jobs/IJobManagerTest.java index fe776b7cec2..d8b41938e78 100644 --- a/runtime/tests/org.eclipse.core.tests.runtime/src/org/eclipse/core/tests/runtime/jobs/IJobManagerTest.java +++ b/runtime/tests/org.eclipse.core.tests.runtime/src/org/eclipse/core/tests/runtime/jobs/IJobManagerTest.java @@ -14,9 +14,7 @@ package org.eclipse.core.tests.runtime.jobs; import static java.util.Collections.synchronizedList; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.collection.IsEmptyCollection.empty; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; @@ -1770,8 +1768,7 @@ private boolean hasPreviousJobStartedRunning() { job.join(); } - assertThat("there have jobs started running before a previously scheduled one", jobsRunningBeforePrevious, - empty()); + assertThat(jobsRunningBeforePrevious).as("job started running before a previously scheduled one").isEmpty(); } @Test @@ -1785,7 +1782,7 @@ public void testReverseOrder() throws InterruptedException { directlyExecutedJob.join(delayInSeconds * 1000 / 2, null); int delayedJobState = delayedJob.getState(); delayedJob.cancel(); - assertThat("delayed job should still be waiting", delayedJobState, is(Job.SLEEPING)); + assertThat(delayedJobState).as("state of delayed job that should be waiting").isEqualTo(Job.SLEEPING); } /** diff --git a/runtime/tests/org.eclipse.core.tests.runtime/src/org/eclipse/core/tests/runtime/jobs/JobTest.java b/runtime/tests/org.eclipse.core.tests.runtime/src/org/eclipse/core/tests/runtime/jobs/JobTest.java index df494074fb0..f9ba3d8c161 100644 --- a/runtime/tests/org.eclipse.core.tests.runtime/src/org/eclipse/core/tests/runtime/jobs/JobTest.java +++ b/runtime/tests/org.eclipse.core.tests.runtime/src/org/eclipse/core/tests/runtime/jobs/JobTest.java @@ -19,10 +19,8 @@ *******************************************************************************/ package org.eclipse.core.tests.runtime.jobs; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.instanceOf; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.lessThan; +import static java.util.function.Predicate.not; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotEquals; @@ -379,7 +377,7 @@ public void testAsynchJobConflict() { } private static void assertThreadType(Job job, Class threadType) { - assertThat("job has unexpected thread type: " + job, job.getThread(), instanceOf(threadType)); + assertThat(job.getThread()).as("type of job %s", job).isInstanceOf(threadType); } /** @@ -1385,7 +1383,7 @@ public void scheduled(IJobChangeEvent event) { Job[] found = Job.getJobManager().find(job); assertEquals("Job should still run", 1, found.length); assertSame("Job should still run", job, found[0]); - assertThat("Expected to see exact one job execution", runCount.get(), is(1L)); + assertThat(runCount.get()).as("number of job executions").isEqualTo(1L); } finally { keepRunning.set(false); } @@ -1611,7 +1609,8 @@ public IStatus run(IProgressMonitor monitor) { job.setProgressGroup(group, 0); job.schedule(); job.join(); - assertThat("job progress has not been reported to group monitor", group.isCanceled()); + assertThat(group).withFailMessage("job progress has not been reported to group monitor") + .matches(IProgressMonitor::isCanceled); group.done(); } @@ -1629,7 +1628,8 @@ public IStatus run(IProgressMonitor monitor) { job.setProgressGroup(group, 0); job.wakeUp(); job.join(); - assertThat("job progress has unexpectedly been reported to group monitor", !group.isCanceled()); + assertThat(group).withFailMessage("job progress has unexpectedly been reported to group monitor") + .matches(not(IProgressMonitor::isCanceled)); } @Test @@ -1648,7 +1648,8 @@ public IStatus run(IProgressMonitor monitor) { barrier.waitForStatus(TestBarrier2.STATUS_RUNNING); job.setProgressGroup(group, 0); job.join(); - assertThat("job progress has unexpectedly been reported to group monitor", !group.isCanceled()); + assertThat(group).withFailMessage("job progress has unexpectedly been reported to group monitor") + .matches(not(IProgressMonitor::isCanceled)); } @Test @@ -1672,7 +1673,8 @@ protected IStatus run(IProgressMonitor monitor) { job.cancel(); barrier.setStatus(TestBarrier2.STATUS_WAIT_FOR_DONE); waitForState(job, Job.NONE); - assertThat("job progress has not been reported to group monitor", group.isCanceled()); + assertThat(group).withFailMessage("job progress has not been reported to group monitor") + .matches(IProgressMonitor::isCanceled); assertEquals("job was unexpectedly not canceled", IStatus.CANCEL, job.getResult().getSeverity()); } @@ -1715,7 +1717,7 @@ protected IStatus run(IProgressMonitor monitor) { public void testSetRule() throws InterruptedException { //setting a scheduling rule for a job after it was already scheduled should throw an exception longJob.setRule(new IdentityRule()); - assertThat(longJob.getRule(), instanceOf(IdentityRule.class)); + assertThat(longJob.getRule()).isInstanceOf(IdentityRule.class); longJob.schedule(1000000); assertThrows(RuntimeException.class, () -> longJob.setRule(new PathRule("/testSetRule"))); @@ -1731,7 +1733,7 @@ public void testSetRule() throws InterruptedException { //after the job has finished executing, the scheduling rule for it can once again be reset longJob.setRule(new PathRule("/testSetRule/B/C/D")); - assertThat(longJob.getRule(), instanceOf(PathRule.class)); + assertThat(longJob.getRule()).isInstanceOf(PathRule.class); longJob.setRule(null); assertNull("job still has a rule assigned: " + longJob, longJob.getRule()); } @@ -1816,8 +1818,8 @@ private void waitForState(Job job, int state) { Thread.yield(); long elapsed = (System.nanoTime() - start) / 1_000_000; // sanity test to avoid hanging tests - assertThat("Timeout waiting for job to change state to " + state + " (current: " + job.getState() - + "): " + job, elapsed, lessThan(timeoutInMs)); + assertThat(elapsed).as("timeout waiting for job to change state to " + state + " (current: " + + job.getState() + "): " + job).isLessThan(timeoutInMs); } } catch (NoSuchMethodException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { diff --git a/runtime/tests/org.eclipse.core.tests.runtime/src/org/eclipse/core/tests/runtime/jobs/OrderedLockTest.java b/runtime/tests/org.eclipse.core.tests.runtime/src/org/eclipse/core/tests/runtime/jobs/OrderedLockTest.java index 1b91087b846..a22ae7f0ef1 100644 --- a/runtime/tests/org.eclipse.core.tests.runtime/src/org/eclipse/core/tests/runtime/jobs/OrderedLockTest.java +++ b/runtime/tests/org.eclipse.core.tests.runtime/src/org/eclipse/core/tests/runtime/jobs/OrderedLockTest.java @@ -13,8 +13,8 @@ *******************************************************************************/ package org.eclipse.core.tests.runtime.jobs; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.lessThan; +import static java.util.function.Predicate.not; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertTrue; import java.lang.management.ManagementFactory; @@ -340,15 +340,15 @@ private void execute(ArrayList allRunnables) { throw new IllegalStateException(e); } checkTimeout(timeoutTime); - assertThat("thread is still alive although join did not timeout", !thread.isAlive()); + assertThat(thread).matches(not(Thread::isAlive), "is not alive"); } } public void checkTimeout(Duration timeoutTime) { Duration currentTime = Duration.ofMillis(System.currentTimeMillis()); if (timeoutTime.minus(currentTime).toMillis() <= 0) { - assertThat("Threads did not end in time. All thread infos begin: ----\n" + getThreadDump() - + "---- All thread infos end.\n", currentTime.toMillis(), lessThan(timeoutTime.toMillis())); + assertThat(currentTime.toMillis()).as("threads did not end in time. All thread infos begin: ----\n" + + getThreadDump() + "---- All thread infos end.\n").isLessThan(timeoutTime.toMillis()); } } diff --git a/team/tests/org.eclipse.team.tests.core/META-INF/MANIFEST.MF b/team/tests/org.eclipse.team.tests.core/META-INF/MANIFEST.MF index c89f3577c6f..16674d810ca 100644 --- a/team/tests/org.eclipse.team.tests.core/META-INF/MANIFEST.MF +++ b/team/tests/org.eclipse.team.tests.core/META-INF/MANIFEST.MF @@ -27,6 +27,7 @@ Require-Bundle: org.eclipse.ui.ide;resolution:=optional, org.eclipse.ui.navigator, org.eclipse.core.filesystem, org.eclipse.compare.tests +Import-Package: org.assertj.core.api Bundle-ActivationPolicy: lazy Eclipse-BundleShape: dir Bundle-RequiredExecutionEnvironment: JavaSE-17 diff --git a/team/tests/org.eclipse.team.tests.core/src/org/eclipse/team/tests/core/RepositoryProviderTests.java b/team/tests/org.eclipse.team.tests.core/src/org/eclipse/team/tests/core/RepositoryProviderTests.java index 7ac33ee04ac..b1850f57961 100644 --- a/team/tests/org.eclipse.team.tests.core/src/org/eclipse/team/tests/core/RepositoryProviderTests.java +++ b/team/tests/org.eclipse.team.tests.core/src/org/eclipse/team/tests/core/RepositoryProviderTests.java @@ -13,12 +13,11 @@ *******************************************************************************/ package org.eclipse.team.tests.core; +import static org.assertj.core.api.Assertions.assertThat; import static org.eclipse.core.resources.ResourcesPlugin.getWorkspace; import static org.eclipse.core.tests.harness.FileSystemHelper.getRandomLocation; import static org.eclipse.core.tests.resources.ResourceTestUtil.buildResources; import static org.eclipse.core.tests.resources.ResourceTestUtil.createInWorkspace; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; @@ -423,7 +422,7 @@ public void testMapFailure() throws CoreException, TeamException { // Test shallow link TeamException shallowLinkException = assertThrows("Link should be disallowed", TeamException.class, () -> RepositoryProvider.map(project, RepositoryProviderWithLinking.TYPE_ID)); - assertThat(shallowLinkException.getStatus().getCode(), is(IResourceStatus.LINKING_NOT_ALLOWED)); + assertThat(shallowLinkException.getStatus().getCode()).isEqualTo(IResourceStatus.LINKING_NOT_ALLOWED); // Test deep link folder.delete(false, null); @@ -431,7 +430,7 @@ public void testMapFailure() throws CoreException, TeamException { folder.createLink(getRandomLocation(), IResource.ALLOW_MISSING_LOCAL, null); TeamException deepLinkException = assertThrows("Link should be disallowed", TeamException.class, () -> RepositoryProvider.map(project, RepositoryProviderWithLinking.TYPE_ID)); - assertThat(deepLinkException.getStatus().getCode(), is(IResourceStatus.LINKING_NOT_ALLOWED)); + assertThat(deepLinkException.getStatus().getCode()).isEqualTo(IResourceStatus.LINKING_NOT_ALLOWED); // Test deep failure when shallow is allowed folder.delete(false, null); @@ -440,7 +439,7 @@ public void testMapFailure() throws CoreException, TeamException { folder.createLink(getRandomLocation(), IResource.ALLOW_MISSING_LOCAL, null); TeamException shallowLinksAllowedException = assertThrows("Link should be disallowed", TeamException.class, () -> RepositoryProvider.map(project, RepositoryProviderWithLinking.TYPE_ID)); - assertThat(shallowLinksAllowedException.getStatus().getCode(), is(IResourceStatus.LINKING_NOT_ALLOWED)); + assertThat(shallowLinksAllowedException.getStatus().getCode()).isEqualTo(IResourceStatus.LINKING_NOT_ALLOWED); } @Test @@ -457,19 +456,19 @@ public void testLinkFailure() throws CoreException, TeamException { // Test shallow link CoreException shallowLinkException = assertThrows("Link should be disallowed", CoreException.class, () -> folder.createLink(getRandomLocation(), IResource.ALLOW_MISSING_LOCAL, null)); - assertThat(shallowLinkException.getStatus().getCode(), is(IResourceStatus.LINKING_NOT_ALLOWED)); + assertThat(shallowLinkException.getStatus().getCode()).isEqualTo(IResourceStatus.LINKING_NOT_ALLOWED); // Test deep link IFolder innerFolder = project.getFolder("folder1/folder2"); CoreException deepLinkException = assertThrows("Link should be disallowed", CoreException.class, () -> innerFolder.createLink(getRandomLocation(), IResource.ALLOW_MISSING_LOCAL, null)); - assertThat(deepLinkException.getStatus().getCode(), is(IResourceStatus.LINKING_NOT_ALLOWED)); + assertThat(deepLinkException.getStatus().getCode()).isEqualTo(IResourceStatus.LINKING_NOT_ALLOWED); // Test deep link when shallow allowed RepositoryProviderWithLinking.setCanHandleLinking(true); CoreException shallowLinkAllowedException = assertThrows("Link should be disallowed", CoreException.class, () -> innerFolder.createLink(getRandomLocation(), IResource.ALLOW_MISSING_LOCAL, null)); - assertThat(shallowLinkAllowedException.getStatus().getCode(), is(IResourceStatus.LINKING_NOT_ALLOWED)); + assertThat(shallowLinkAllowedException.getStatus().getCode()).isEqualTo(IResourceStatus.LINKING_NOT_ALLOWED); } @Test diff --git a/team/tests/org.eclipse.team.tests.core/src/org/eclipse/team/tests/ui/SaveableCompareEditorInputTest.java b/team/tests/org.eclipse.team.tests.core/src/org/eclipse/team/tests/ui/SaveableCompareEditorInputTest.java index 3a4c6377a74..507a9cd026f 100644 --- a/team/tests/org.eclipse.team.tests.core/src/org/eclipse/team/tests/ui/SaveableCompareEditorInputTest.java +++ b/team/tests/org.eclipse.team.tests.core/src/org/eclipse/team/tests/ui/SaveableCompareEditorInputTest.java @@ -14,12 +14,11 @@ package org.eclipse.team.tests.ui; import static java.util.Collections.synchronizedList; +import static org.assertj.core.api.Assertions.assertThat; import static org.eclipse.core.resources.ResourcesPlugin.getWorkspace; import static org.eclipse.core.tests.resources.ResourceTestUtil.compareContent; import static org.eclipse.core.tests.resources.ResourceTestUtil.createInWorkspace; import static org.eclipse.core.tests.resources.ResourceTestUtil.createInputStream; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.empty; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; @@ -98,7 +97,7 @@ public void setUp() throws Exception { public void tearDown() throws Exception { // remove log listener Platform.removeLogListener(logListener); - assertThat("Unexpected errors in log listener", errorsInListener, empty()); + assertThat(errorsInListener).as("logged errors").isEmpty(); } private class TestFileElement implements ITypedElement {