diff --git a/.idea/libraries/assertj.xml b/.idea/libraries/assertj.xml new file mode 100644 index 0000000000000..7d00f8040dc88 --- /dev/null +++ b/.idea/libraries/assertj.xml @@ -0,0 +1,11 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/java/client/client.iml b/java/client/client.iml index 6a6da69a15555..2481842a3ad2f 100644 --- a/java/client/client.iml +++ b/java/client/client.iml @@ -43,6 +43,7 @@ + diff --git a/java/client/test/org/openqa/selenium/AlertsTest.java b/java/client/test/org/openqa/selenium/AlertsTest.java index 1067f3a4683f0..757552725b7e6 100644 --- a/java/client/test/org/openqa/selenium/AlertsTest.java +++ b/java/client/test/org/openqa/selenium/AlertsTest.java @@ -17,11 +17,8 @@ package org.openqa.selenium; -import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.instanceOf; -import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assume.assumeFalse; import static org.openqa.selenium.WaitingConditions.newWindowIsOpened; import static org.openqa.selenium.support.ui.ExpectedConditions.alertIsPresent; @@ -33,10 +30,10 @@ import static org.openqa.selenium.testing.Driver.IE; import static org.openqa.selenium.testing.Driver.MARIONETTE; import static org.openqa.selenium.testing.Driver.SAFARI; -import static org.openqa.selenium.testing.TestUtilities.catchThrowable; import static org.openqa.selenium.testing.TestUtilities.getFirefoxVersion; import static org.openqa.selenium.testing.TestUtilities.isFirefox; +import org.assertj.core.api.Assumptions; import org.junit.After; import org.junit.Test; import org.openqa.selenium.environment.webserver.Page; @@ -93,7 +90,7 @@ public void testShouldBeAbleToOverrideTheWindowAlertMethod() { driver.findElement(By.id("alert")).click(); // If we can perform any action, we're good to go - assertEquals("Testing Alerts", driver.getTitle()); + assertThat(driver.getTitle()).isEqualTo("Testing Alerts"); } @Test @@ -105,7 +102,7 @@ public void testShouldAllowUsersToAcceptAnAlertManually() { alert.accept(); // If we can perform any action, we're good to go - assertEquals("Testing Alerts", driver.getTitle()); + assertThat(driver.getTitle()).isEqualTo("Testing Alerts"); } @Test @@ -115,8 +112,8 @@ public void testShouldThrowIllegalArgumentExceptionWhenKeysNull() { driver.findElement(By.id("alert")).click(); Alert alert = wait.until(alertIsPresent()); try { - Throwable t = catchThrowable(() -> alert.sendKeys(null)); - assertThat(t, instanceOf(IllegalArgumentException.class)); + assertThatExceptionOfType(IllegalArgumentException.class) + .isThrownBy(() -> alert.sendKeys(null)); } finally { alert.accept(); } @@ -131,7 +128,7 @@ public void testShouldAllowUsersToAcceptAnAlertWithNoTextManually() { alert.accept(); // If we can perform any action, we're good to go - assertEquals("Testing Alerts", driver.getTitle()); + assertThat(driver.getTitle()).isEqualTo("Testing Alerts"); } @NeedsLocalEnvironment(reason = "Carefully timing based") @@ -154,7 +151,7 @@ public void testShouldGetTextOfAlertOpenedInSetTimeout() { // and only if it happens before the alert actually loads. Alert alert = driver.switchTo().alert(); try { - assertEquals("Slow", alert.getText()); + assertThat(alert.getText()).isEqualTo("Slow"); } finally { alert.accept(); } @@ -169,7 +166,7 @@ public void testShouldAllowUsersToDismissAnAlertManually() { alert.dismiss(); // If we can perform any action, we're good to go - assertEquals("Testing Alerts", driver.getTitle()); + assertThat(driver.getTitle()).isEqualTo("Testing Alerts"); } @Test @@ -181,7 +178,7 @@ public void testShouldAllowAUserToAcceptAPrompt() { alert.accept(); // If we can perform any action, we're good to go - assertEquals("Testing Prompt", driver.getTitle()); + assertThat(driver.getTitle()).isEqualTo("Testing Prompt"); } @Test @@ -193,7 +190,7 @@ public void testShouldAllowAUserToDismissAPrompt() { alert.dismiss(); // If we can perform any action, we're good to go - assertEquals("Testing Prompt", driver.getTitle()); + assertThat(driver.getTitle()).isEqualTo("Testing Prompt"); } @Test @@ -218,8 +215,8 @@ public void testSettingTheValueOfAnAlertThrows() { Alert alert = wait.until(alertIsPresent()); try { - Throwable t = catchThrowable(() -> alert.sendKeys("cheese")); - assertThat(t, instanceOf(ElementNotInteractableException.class)); + assertThatExceptionOfType(ElementNotInteractableException.class) + .isThrownBy(() -> alert.sendKeys("cheese")); } finally { alert.accept(); } @@ -234,7 +231,7 @@ public void testShouldAllowTheUserToGetTheTextOfAnAlert() { String value = alert.getText(); alert.accept(); - assertEquals("cheese", value); + assertThat(value).isEqualTo("cheese"); } @Test @@ -246,7 +243,7 @@ public void testShouldAllowTheUserToGetTheTextOfAPrompt() { String value = alert.getText(); alert.accept(); - assertEquals("Enter something", value); + assertThat(value).isEqualTo("Enter something"); } @Test @@ -257,8 +254,8 @@ public void testAlertShouldNotAllowAdditionalCommandsIfDismissed() { Alert alert = wait.until(alertIsPresent()); alert.accept(); - Throwable t = catchThrowable(alert::getText); - assertThat(t, instanceOf(NoAlertPresentException.class)); + assertThatExceptionOfType(NoAlertPresentException.class) + .isThrownBy(alert::getText); } @SwitchToTopAfterTest @@ -276,7 +273,7 @@ public void testShouldAllowUsersToAcceptAnAlertInAFrame() { alert.accept(); // If we can perform any action, we're good to go - assertEquals("Testing Alerts", driver.getTitle()); + assertThat(driver.getTitle()).isEqualTo("Testing Alerts"); } @SwitchToTopAfterTest @@ -297,15 +294,15 @@ public void testShouldAllowUsersToAcceptAnAlertInANestedFrame() { alert.accept(); // If we can perform any action, we're good to go - assertEquals("Testing Alerts", driver.getTitle()); + assertThat(driver.getTitle()).isEqualTo("Testing Alerts"); } @Test public void testSwitchingToMissingAlertThrows() { driver.get(alertPage("cheese")); - Throwable t = catchThrowable(() -> driver.switchTo().alert()); - assertThat(t, instanceOf(NoAlertPresentException.class)); + assertThatExceptionOfType(NoAlertPresentException.class) + .isThrownBy(() -> driver.switchTo().alert()); } @Test @@ -321,8 +318,8 @@ public void testSwitchingToMissingAlertInAClosedWindowThrows() { wait.until(ableToSwitchToWindow("newwindow")); driver.close(); - Throwable t = catchThrowable(() -> driver.switchTo().alert()); - assertThat(t, instanceOf(NoSuchWindowException.class)); + assertThatExceptionOfType(NoSuchWindowException.class) + .isThrownBy(() -> driver.switchTo().alert()); } finally { driver.switchTo().window(mainWindow); @@ -394,7 +391,7 @@ public void testShouldHandleAlertOnPageLoad() { String value = alert.getText(); alert.accept(); - assertEquals("onload", value); + assertThat(value).isEqualTo("onload"); wait.until(textInElementLocated(By.tagName("p"), "Page with onload event handler")); } @@ -409,7 +406,7 @@ public void testShouldHandleAlertOnPageLoadUsingGet() { String value = alert.getText(); alert.accept(); - assertEquals("onload", value); + assertThat(value).isEqualTo("onload"); wait.until(textInElementLocated(By.tagName("p"), "Page with onload event handler")); } @@ -433,8 +430,8 @@ public void testShouldNotHandleAlertInAnotherWindow() { driver.findElement(By.id("open-new-window")).click(); wait.until(newWindowIsOpened(currentWindowHandles)); - Throwable t = catchThrowable(() -> wait.until(alertIsPresent())); - assertThat(t, instanceOf(TimeoutException.class)); + assertThatExceptionOfType(TimeoutException.class) + .isThrownBy(() -> wait.until(alertIsPresent())); } finally { driver.switchTo().window("newwindow"); @@ -466,7 +463,7 @@ public void testShouldHandleAlertOnPageUnload() { String value = alert.getText(); alert.accept(); - assertEquals("onbeforeunload", value); + assertThat(value).isEqualTo("onbeforeunload"); wait.until(textInElementLocated(By.id("link"), "open new page")); } @@ -513,7 +510,7 @@ public void testShouldHandleAlertOnWindowClose() { String value = alert.getText(); alert.accept(); - assertEquals("onbeforeunload", value); + assertThat(value).isEqualTo("onbeforeunload"); } finally { driver.switchTo().window(mainWindow); @@ -533,10 +530,10 @@ public void testIncludesAlertTextInUnhandledAlertException() { driver.findElement(By.id("alert")).click(); wait.until(alertIsPresent()); - Throwable t = catchThrowable(driver::getTitle); - assertThat(t, instanceOf(UnhandledAlertException.class)); - assertThat(((UnhandledAlertException) t).getAlertText(), is("cheese")); - assertThat(t.getMessage(), containsString("cheese")); + assertThatExceptionOfType(UnhandledAlertException.class) + .isThrownBy(driver::getTitle) + .withMessage("cheese") + .satisfies(ex -> assertThat(ex.getAlertText()).isEqualTo("cheese")); } @NoDriverAfterTest @@ -564,8 +561,8 @@ public void shouldHandleAlertOnFormSubmit() { String value = alert.getText(); alert.accept(); - assertEquals("Tasty cheese", value); - assertEquals("Testing Alerts", driver.getTitle()); + assertThat(value).isEqualTo("Tasty cheese"); + assertThat(driver.getTitle()).isEqualTo("Testing Alerts"); } private static ExpectedCondition textInElementLocated( diff --git a/java/client/test/org/openqa/selenium/ArchitectureTest.java b/java/client/test/org/openqa/selenium/ArchitectureTest.java index 0987d6845e13c..f1e6aef55f7da 100644 --- a/java/client/test/org/openqa/selenium/ArchitectureTest.java +++ b/java/client/test/org/openqa/selenium/ArchitectureTest.java @@ -17,152 +17,148 @@ package org.openqa.selenium; -import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.instanceOf; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; -import static org.openqa.selenium.testing.TestUtilities.catchThrowable; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.openqa.selenium.Architecture.ANY; +import static org.openqa.selenium.Architecture.ARM; +import static org.openqa.selenium.Architecture.X64; +import static org.openqa.selenium.Architecture.X86; import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; -@RunWith(JUnit4.class) public class ArchitectureTest { @Test public void anyMatchesX86() { - assertTrue(Architecture.ANY.is(Architecture.X86)); + assertThat(ANY.is(X86)).isTrue(); } @Test public void anyMatchesX64() { - assertTrue(Architecture.ANY.is(Architecture.X64)); + assertThat(ANY.is(X64)).isTrue(); } @Test public void anyMatchesARM() { - assertTrue(Architecture.ANY.is(Architecture.ARM)); + assertThat(ANY.is(ARM)).isTrue(); } @Test public void anyMatchesANY() { - assertTrue(Architecture.ANY.is(Architecture.ANY)); + assertThat(ANY.is(ANY)).isTrue(); } @Test public void currentArchitecture() { Architecture current = Architecture.getCurrent(); - assertNotNull(current); - assertFalse(current.is(Architecture.ANY)); + assertThat(current).isNotNull(); + assertThat(current.is(ANY)).isFalse(); } @Test public void determineArchI386() { - assertTrue(Architecture.extractFromSysProperty("i386").is(Architecture.X86)); + assertThat(Architecture.extractFromSysProperty("i386").is(X86)).isTrue(); } @Test public void determineArchIA32() { - assertTrue(Architecture.extractFromSysProperty("ia32").is(Architecture.X86)); + assertThat(Architecture.extractFromSysProperty("ia32").is(X86)).isTrue(); } @Test public void determineArchI686() { - assertTrue(Architecture.extractFromSysProperty("i686").is(Architecture.X86)); + assertThat(Architecture.extractFromSysProperty("i686").is(X86)).isTrue(); } @Test public void determineArchI486() { - assertTrue(Architecture.extractFromSysProperty("i486").is(Architecture.X86)); + assertThat(Architecture.extractFromSysProperty("i486").is(X86)).isTrue(); } @Test public void determineArchI86() { - assertTrue(Architecture.extractFromSysProperty("i86").is(Architecture.X86)); + assertThat(Architecture.extractFromSysProperty("i86").is(X86)).isTrue(); } @Test public void determineArchPentium() { - assertTrue(Architecture.extractFromSysProperty("pentium").is(Architecture.X86)); + assertThat(Architecture.extractFromSysProperty("pentium").is(X86)).isTrue(); } @Test public void determineArchPentiumPro() { - assertTrue(Architecture.extractFromSysProperty("pentium_pro").is(Architecture.X86)); + assertThat(Architecture.extractFromSysProperty("pentium_pro").is(X86)).isTrue(); } @Test public void determineArchPentiumProMmx() { - assertTrue(Architecture.extractFromSysProperty("pentium_pro+mmx").is(Architecture.X86)); + assertThat(Architecture.extractFromSysProperty("pentium_pro+mmx").is(X86)) + .isTrue(); } @Test public void determineArchPentiumMmx() { - assertTrue(Architecture.extractFromSysProperty("pentium+mmx").is(Architecture.X86)); + assertThat(Architecture.extractFromSysProperty("pentium+mmx").is(X86)).isTrue(); } @Test public void determineArchAMD64() { - assertTrue(Architecture.extractFromSysProperty("amd64").is(Architecture.X64)); + assertThat(Architecture.extractFromSysProperty("amd64").is(X64)).isTrue(); } @Test public void determineArchIA64() { - assertTrue(Architecture.extractFromSysProperty("ia64").is(Architecture.X64)); + assertThat(Architecture.extractFromSysProperty("ia64").is(X64)).isTrue(); } @Test public void determineArchARM() { - assertTrue(Architecture.extractFromSysProperty("arm").is(Architecture.ARM)); + assertThat(Architecture.extractFromSysProperty("arm").is(ARM)).isTrue(); } @Test public void determineArchEmpty() { - Throwable t = catchThrowable(() -> Architecture.extractFromSysProperty("")); - assertThat(t, instanceOf(UnsupportedOperationException.class)); - assertThat(t.getMessage(), containsString("Unknown architecture")); + assertThatExceptionOfType(UnsupportedOperationException.class) + .isThrownBy(() -> Architecture.extractFromSysProperty("")) + .withMessageContaining("Unknown architecture"); } @Test public void determineArchBogus() { - Throwable t = catchThrowable(() -> Architecture.extractFromSysProperty("hoobaflooba")); - assertThat(t, instanceOf(UnsupportedOperationException.class)); - assertThat(t.getMessage(), containsString("Unknown architecture")); + assertThatExceptionOfType(UnsupportedOperationException.class) + .isThrownBy(() -> Architecture.extractFromSysProperty("hoobaflooba")) + .withMessageContaining("Unknown architecture"); } @Test public void determineArchMixedCasing() { - assertTrue(Architecture.extractFromSysProperty("AmD64").is(Architecture.X64)); + assertThat(Architecture.extractFromSysProperty("AmD64").is(X64)).isTrue(); } @Test public void dataModelIs32Or64BitOnCurrentArchitecture() { int model = Architecture.getCurrent().getDataModel(); - assertTrue(model == 32 || model == 64); + assertThat(model == 32 || model == 64).isTrue(); } @Test public void x86DataModelIs32Bit() { - assertEquals(32, Architecture.X86.getDataModel()); + assertThat(X86.getDataModel()).isEqualTo(32); } @Test public void x64DataModelIs64Bit() { - assertEquals(64, Architecture.X64.getDataModel()); + assertThat(X64.getDataModel()).isEqualTo(64); } @Test public void armDataModelIs64Bit() { - assertEquals(64, Architecture.ARM.getDataModel()); + assertThat(ARM.getDataModel()).isEqualTo(64); } @Test public void anyDataModelIs64Bit() { - assertEquals(64, Architecture.ANY.getDataModel()); + assertThat(ANY.getDataModel()).isEqualTo(64); } } diff --git a/java/client/test/org/openqa/selenium/AtomsInjectionTest.java b/java/client/test/org/openqa/selenium/AtomsInjectionTest.java index e374c7b0773fe..780253c7bb699 100644 --- a/java/client/test/org/openqa/selenium/AtomsInjectionTest.java +++ b/java/client/test/org/openqa/selenium/AtomsInjectionTest.java @@ -17,7 +17,7 @@ package org.openqa.selenium; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; import org.openqa.selenium.testing.JUnit4TestBase; @@ -28,6 +28,6 @@ public class AtomsInjectionTest extends JUnit4TestBase { public void testInjectingAtomShouldNotTrampleOnUnderscoreGlobal() { driver.get(pages.underscorePage); driver.findElement(By.tagName("body")); - assertEquals("123", ((JavascriptExecutor) driver).executeScript("return _.join('');")); + assertThat(((JavascriptExecutor) driver).executeScript("return _.join('');")).isEqualTo("123"); } } diff --git a/java/client/test/org/openqa/selenium/BUCK b/java/client/test/org/openqa/selenium/BUCK index cce37e4e6842c..c61b65e287a90 100644 --- a/java/client/test/org/openqa/selenium/BUCK +++ b/java/client/test/org/openqa/selenium/BUCK @@ -87,7 +87,7 @@ java_library(name = 'tests', '//java/client/test/org/openqa/selenium/testing/drivers:drivers', '//third_party/java/gson:gson', '//third_party/java/guava:guava', - '//third_party/java/hamcrest:hamcrest-library', + '//third_party/java/assertj:assertj', '//third_party/java/jetty:jetty', '//third_party/java/junit:junit', '//third_party/java/mockito:mockito-core', diff --git a/java/client/test/org/openqa/selenium/ByTest.java b/java/client/test/org/openqa/selenium/ByTest.java index e912565f5fa92..c013b9c831fc0 100644 --- a/java/client/test/org/openqa/selenium/ByTest.java +++ b/java/client/test/org/openqa/selenium/ByTest.java @@ -17,15 +17,20 @@ package org.openqa.selenium; -import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.openqa.selenium.By.ByClassName; +import static org.openqa.selenium.By.ByCssSelector; +import static org.openqa.selenium.By.ById; +import static org.openqa.selenium.By.ByLinkText; +import static org.openqa.selenium.By.ByName; +import static org.openqa.selenium.By.ByPartialLinkText; +import static org.openqa.selenium.By.ByTagName; +import static org.openqa.selenium.By.ByXPath; import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; import org.openqa.selenium.internal.FindsByClassName; import org.openqa.selenium.internal.FindsById; import org.openqa.selenium.internal.FindsByLinkText; @@ -35,7 +40,6 @@ import java.util.List; -@RunWith(JUnit4.class) public class ByTest { @Test @@ -138,14 +142,14 @@ public void searchesByXPathIfFindingByClassNameNotSupported() { @Test public void innerClassesArePublicSoThatTheyCanBeReusedElsewhere() { - assertThat(new By.ByXPath("a").toString(), equalTo("By.xpath: a")); - assertThat(new By.ById("a").toString(), equalTo("By.id: a")); - assertThat(new By.ByClassName("a").toString(), equalTo("By.className: a")); - assertThat(new By.ByLinkText("a").toString(), equalTo("By.linkText: a")); - assertThat(new By.ByName("a").toString(), equalTo("By.name: a")); - assertThat(new By.ByTagName("a").toString(), equalTo("By.tagName: a")); - assertThat(new By.ByCssSelector("a").toString(), equalTo("By.cssSelector: a")); - assertThat(new By.ByPartialLinkText("a").toString(), equalTo("By.partialLinkText: a")); + assertThat(new ByXPath("a").toString()).isEqualTo("By.xpath: a"); + assertThat(new ById("a").toString()).isEqualTo("By.id: a"); + assertThat(new ByClassName("a").toString()).isEqualTo("By.className: a"); + assertThat(new ByLinkText("a").toString()).isEqualTo("By.linkText: a"); + assertThat(new ByName("a").toString()).isEqualTo("By.name: a"); + assertThat(new ByTagName("a").toString()).isEqualTo("By.tagName: a"); + assertThat(new ByCssSelector("a").toString()).isEqualTo("By.cssSelector: a"); + assertThat(new ByPartialLinkText("a").toString()).isEqualTo("By.partialLinkText: a"); } // See http://code.google.com/p/selenium/issues/detail?id=2917 diff --git a/java/client/test/org/openqa/selenium/ChildrenFindingTest.java b/java/client/test/org/openqa/selenium/ChildrenFindingTest.java index d8b7ab9c6beac..d7eee1a6487e3 100644 --- a/java/client/test/org/openqa/selenium/ChildrenFindingTest.java +++ b/java/client/test/org/openqa/selenium/ChildrenFindingTest.java @@ -17,19 +17,12 @@ package org.openqa.selenium; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.instanceOf; -import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.openqa.selenium.testing.Driver.CHROME; import static org.openqa.selenium.testing.Driver.SAFARI; -import static org.openqa.selenium.testing.TestUtilities.catchThrowable; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.openqa.selenium.testing.Ignore; import org.openqa.selenium.testing.JUnit4TestBase; @@ -38,15 +31,12 @@ public class ChildrenFindingTest extends JUnit4TestBase { - @Rule - public final ExpectedException expectedException = ExpectedException.none(); - @Test public void testFindElementByXPath() { driver.get(pages.nestedPage); WebElement element = driver.findElement(By.name("form2")); WebElement child = element.findElement(By.xpath("select")); - assertThat(child.getAttribute("id"), is("2")); + assertThat(child.getAttribute("id")).isEqualTo("2"); } @Test @@ -55,7 +45,7 @@ public void testFindingElementsOnElementByXPathShouldFindTopLevelElements() { WebElement parent = driver.findElement(By.id("multiline")); List allPs = driver.findElements(By.xpath("//p")); List children = parent.findElements(By.xpath("//p")); - assertEquals(allPs.size(), children.size()); + assertThat(allPs.size()).isEqualTo(children.size()); } @Test @@ -63,16 +53,16 @@ public void testFindingDotSlashElementsOnElementByXPathShouldFindNotTopLevelElem driver.get(pages.simpleTestPage); WebElement parent = driver.findElement(By.id("multiline")); List children = parent.findElements(By.xpath("./p")); - assertEquals(1, children.size()); - assertEquals("A div containing", children.get(0).getText()); + assertThat(children).hasSize(1); + assertThat(children.get(0).getText()).isEqualTo("A div containing"); } @Test public void testFindElementByXPathWhenNoMatch() { driver.get(pages.nestedPage); WebElement element = driver.findElement(By.name("form2")); - Throwable t = catchThrowable(() -> element.findElement(By.xpath(".//select/x"))); - assertThat(t, instanceOf(NoSuchElementException.class)); + assertThatExceptionOfType(NoSuchElementException.class) + .isThrownBy(() -> element.findElement(By.xpath(".//select/x"))); } @Test @@ -80,9 +70,9 @@ public void testFindElementsByXPath() { driver.get(pages.nestedPage); WebElement element = driver.findElement(By.name("form2")); List children = element.findElements(By.xpath("select/option")); - assertThat(children.size(), is(8)); - assertThat(children.get(0).getText(), is("One")); - assertThat(children.get(1).getText(), is("Two")); + assertThat(children).hasSize(8); + assertThat(children.get(0).getText()).isEqualTo("One"); + assertThat(children.get(1).getText()).isEqualTo("Two"); } @Test @@ -90,7 +80,7 @@ public void testFindElementsByXPathWhenNoMatch() { driver.get(pages.nestedPage); WebElement element = driver.findElement(By.name("form2")); List children = element.findElements(By.xpath(".//select/x")); - assertEquals(0, children.size()); + assertThat(children).hasSize(0); } @Test @@ -98,7 +88,7 @@ public void testFindElementByName() { driver.get(pages.nestedPage); WebElement element = driver.findElement(By.name("form2")); WebElement child = element.findElement(By.name("selectomatic")); - assertThat(child.getAttribute("id"), is("2")); + assertThat(child.getAttribute("id")).isEqualTo("2"); } @Test @@ -106,7 +96,7 @@ public void testFindElementsByName() { driver.get(pages.nestedPage); WebElement element = driver.findElement(By.name("form2")); List children = element.findElements(By.name("selectomatic")); - assertThat(children.size(), is(2)); + assertThat(children).hasSize(2); } @Test @@ -114,7 +104,7 @@ public void testFindElementById() { driver.get(pages.nestedPage); WebElement element = driver.findElement(By.name("form2")); WebElement child = element.findElement(By.id("2")); - assertThat(child.getAttribute("name"), is("selectomatic")); + assertThat(child.getAttribute("name")).isEqualTo("selectomatic"); } @Test @@ -122,7 +112,7 @@ public void testFindElementByIdWhenMultipleMatchesExist() { driver.get(pages.nestedPage); WebElement element = driver.findElement(By.id("test_id_div")); WebElement child = element.findElement(By.id("test_id")); - assertThat(child.getText(), is("inside")); + assertThat(child.getText()).isEqualTo("inside"); } @Test @@ -132,17 +122,17 @@ public void testFindElementByIdWhenIdContainsNonAlphanumericCharacters() { driver.get(pages.nestedPage); WebElement element = driver.findElement(By.id("test_special_chars")); WebElement childWithSpaces = element.findElement(By.id("white space")); - assertThat(childWithSpaces.getText(), is("space")); + assertThat(childWithSpaces.getText()).isEqualTo("space"); WebElement childWithCssChars = element.findElement(By.id("css#.chars")); - assertThat(childWithCssChars.getText(), is("css escapes")); + assertThat(childWithCssChars.getText()).isEqualTo("css escapes"); } @Test public void testFindElementByIdWhenNoMatchInContext() { driver.get(pages.nestedPage); WebElement element = driver.findElement(By.id("test_id_div")); - Throwable t = catchThrowable(() -> element.findElement(By.id("test_id_out"))); - assertThat(t, instanceOf(NoSuchElementException.class)); + assertThatExceptionOfType(NoSuchElementException.class) + .isThrownBy(() -> element.findElement(By.id("test_id_out"))); } @Test @@ -150,7 +140,7 @@ public void testFindElementsById() { driver.get(pages.nestedPage); WebElement element = driver.findElement(By.name("form2")); List children = element.findElements(By.id("2")); - assertThat(children.size(), is(2)); + assertThat(children).hasSize(2); } @Test @@ -160,9 +150,9 @@ public void testFindElementsByIdWithNonAlphanumericCharacters() { driver.get(pages.nestedPage); WebElement element = driver.findElement(By.id("test_special_chars")); List children = element.findElements(By.id("white space")); - assertThat(children.size(), is(1)); + assertThat(children).hasSize(1); List children2 = element.findElements(By.id("css#.chars")); - assertThat(children2.size(), is(1)); + assertThat(children2).hasSize(1); } @Test @@ -171,8 +161,8 @@ public void testFindElementByLinkText() { WebElement element = driver.findElement(By.name("div1")); WebElement child = element.findElement(By.linkText("hello world")); List invalidChildren = element.findElements(By.linkText("HellO WorLD")); - assertEquals(0, invalidChildren.size()); - assertThat(child.getAttribute("name"), is("link1")); + assertThat(invalidChildren).hasSize(0); + assertThat(child.getAttribute("name")).isEqualTo("link1"); } @Test @@ -181,9 +171,9 @@ public void testFindElementsByLinkTest() { WebElement element = driver.findElement(By.name("div1")); List elements = element.findElements(By.linkText("hello world")); - assertEquals(2, elements.size()); - assertThat(elements.get(0).getAttribute("name"), is("link1")); - assertThat(elements.get(1).getAttribute("name"), is("link2")); + assertThat(elements).hasSize(2); + assertThat(elements.get(0).getAttribute("name")).isEqualTo("link1"); + assertThat(elements.get(1).getAttribute("name")).isEqualTo("link2"); } @Test @@ -191,7 +181,7 @@ public void testShouldFindChildElementsById() { driver.get(pages.nestedPage); WebElement parent = driver.findElement(By.id("test_id_div")); WebElement element = parent.findElement(By.id("test_id")); - assertEquals("inside", element.getText()); + assertThat(element.getText()).isEqualTo("inside"); } @Test @@ -200,9 +190,9 @@ public void testShouldNotReturnRootElementWhenFindingChildrenById() { driver.get(pages.nestedPage); WebElement parent = driver.findElement(By.id("test_id")); - assertEquals(0, parent.findElements(By.id("test_id")).size()); - expectedException.expect(NoSuchElementException.class); - parent.findElement(By.id("test_id")); + assertThat(parent.findElements(By.id("test_id"))).hasSize(0); + assertThatExceptionOfType(NoSuchElementException.class) + .isThrownBy(() -> parent.findElement(By.id("test_id"))); } @Test @@ -212,7 +202,7 @@ public void testShouldFindChildElementsByClassName() { WebElement element = parent.findElement(By.className("one")); - assertEquals("Find me", element.getText()); + assertThat(element.getText()).isEqualTo("Find me"); } @Test @@ -222,7 +212,7 @@ public void testShouldFindChildrenByClassName() { List elements = parent.findElements(By.className("one")); - assertEquals(2, elements.size()); + assertThat(elements).hasSize(2); } @Test @@ -232,7 +222,7 @@ public void testShouldFindChildElementsByTagName() { WebElement element = parent.findElement(By.tagName("a")); - assertEquals("link1", element.getAttribute("name")); + assertThat(element.getAttribute("name")).isEqualTo("link1"); } @Test @@ -242,7 +232,7 @@ public void testShouldFindChildrenByTagName() { List elements = parent.findElements(By.tagName("a")); - assertEquals(2, elements.size()); + assertThat(elements).hasSize(2); } @Test @@ -252,7 +242,7 @@ public void testShouldBeAbleToFindAnElementByCssSelector() { WebElement element = parent.findElement(By.cssSelector("*[name=\"selectomatic\"]")); - assertEquals("2", element.getAttribute("id")); + assertThat(element.getAttribute("id")).isEqualTo("2"); } @Test @@ -262,7 +252,7 @@ public void testShouldBeAbleToFindAnElementByCss3Selector() { WebElement element = parent.findElement(By.cssSelector("*[name^=\"selecto\"]")); - assertEquals("2", element.getAttribute("id")); + assertThat(element.getAttribute("id")).isEqualTo("2"); } @Test @@ -272,7 +262,7 @@ public void testShouldBeAbleToFindElementsByCssSelector() { List elements = parent.findElements(By.cssSelector("*[name=\"selectomatic\"]")); - assertEquals(2, elements.size()); + assertThat(elements).hasSize(2); } @Test @@ -281,7 +271,7 @@ public void testShouldBeAbleToFindChildrenOfANode() { List elements = driver.findElements(By.xpath("/html/head")); WebElement head = elements.get(0); List importedScripts = head.findElements(By.tagName("script")); - assertThat(importedScripts.size(), equalTo(3)); + assertThat(importedScripts).hasSize(3); } @Test @@ -290,7 +280,7 @@ public void testReturnAnEmptyListWhenThereAreNoChildrenOfANode() { WebElement table = driver.findElement(By.id("table")); List rows = table.findElements(By.tagName("tr")); - assertThat(rows.size(), equalTo(0)); + assertThat(rows).hasSize(0); } @Test @@ -304,8 +294,8 @@ public void testShouldFindGrandChildren() { public void testShouldNotFindElementOutSideTree() { driver.get(pages.formPage); WebElement element = driver.findElement(By.name("login")); - Throwable t = catchThrowable(() -> element.findElement(By.name("x"))); - assertThat(t, instanceOf(NoSuchElementException.class)); + assertThatExceptionOfType(NoSuchElementException.class) + .isThrownBy(() -> element.findElement(By.name("x"))); } @Test @@ -313,8 +303,8 @@ public void testFindingByTagNameShouldNotIncludeParentElementIfSameTagType() { driver.get(pages.xhtmlTestPage); WebElement parent = driver.findElement(By.id("my_span")); - assertEquals(2, parent.findElements(By.tagName("div")).size()); - assertEquals(2, parent.findElements(By.tagName("span")).size()); + assertThat(parent.findElements(By.tagName("div"))).hasSize(2); + assertThat(parent.findElements(By.tagName("span"))).hasSize(2); } @Test @@ -323,7 +313,7 @@ public void testFindingByCssShouldNotIncludeParentElementIfSameTagType() { WebElement parent = driver.findElement(By.cssSelector("div#parent")); WebElement child = parent.findElement(By.cssSelector("div")); - assertEquals("child", child.getAttribute("id")); + assertThat(child.getAttribute("id")).isEqualTo("child"); } @Test @@ -332,8 +322,7 @@ public void testFindMultipleElements() { WebElement elem = driver.findElement(By.id("links")); List elements = elem.findElements(By.partialLinkText("link")); - assertNotNull(elements); - assertEquals(6, elements.size()); + assertThat(elements).hasSize(6); } @Test @@ -343,7 +332,7 @@ public void testLinkWithLeadingSpaces() { WebElement elem = driver.findElement(By.id("links")); WebElement res = elem.findElement(By.partialLinkText("link with leading space")); - assertEquals("link with leading space", res.getText()); + assertThat(res.getText()).isEqualTo("link with leading space"); } @Test @@ -353,7 +342,7 @@ public void testLinkWithTrailingSpace() { WebElement elem = driver.findElement(By.id("links")); WebElement res = elem.findElement(By.partialLinkText("link with trailing space")); - assertEquals("link with trailing space", res.getText()); + assertThat(res.getText()).isEqualTo("link with trailing space"); } @Test @@ -362,7 +351,7 @@ public void testElementCanGetLinkByLinkTestIgnoringTrailingWhitespace() { WebElement elem = driver.findElement(By.id("links")); WebElement link = elem.findElement(By.linkText("link with trailing space")); - assertEquals("linkWithTrailingSpace", link.getAttribute("id")); + assertThat(link.getAttribute("id")).isEqualTo("linkWithTrailingSpace"); } } diff --git a/java/client/test/org/openqa/selenium/ClearTest.java b/java/client/test/org/openqa/selenium/ClearTest.java index eab3eee5f0e81..2317d4d0e14e5 100644 --- a/java/client/test/org/openqa/selenium/ClearTest.java +++ b/java/client/test/org/openqa/selenium/ClearTest.java @@ -17,16 +17,14 @@ package org.openqa.selenium; -import static org.hamcrest.CoreMatchers.instanceOf; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.openqa.selenium.testing.Driver.CHROME; import static org.openqa.selenium.testing.Driver.FIREFOX; import static org.openqa.selenium.testing.Driver.HTMLUNIT; import static org.openqa.selenium.testing.Driver.IE; import static org.openqa.selenium.testing.Driver.MARIONETTE; import static org.openqa.selenium.testing.Driver.SAFARI; -import static org.openqa.selenium.testing.TestUtilities.catchThrowable; import org.junit.Test; import org.openqa.selenium.testing.JUnit4TestBase; @@ -39,24 +37,24 @@ public void testWritableTextInputShouldClear() { driver.get(pages.readOnlyPage); WebElement element = driver.findElement(By.id("writableTextInput")); element.clear(); - assertEquals("", element.getAttribute("value")); + assertThat(element.getAttribute("value")).isEqualTo(""); } @Test public void testTextInputShouldNotClearWhenDisabled() { driver.get(pages.readOnlyPage); WebElement element = driver.findElement(By.id("textInputnotenabled")); - assertEquals(false, element.isEnabled()); - Throwable t = catchThrowable(element::clear); - assertThat(t, instanceOf(InvalidElementStateException.class)); + assertThat(element.isEnabled()).isFalse(); + assertThatExceptionOfType(InvalidElementStateException.class) + .isThrownBy(element::clear); } @Test public void testTextInputShouldNotClearWhenReadOnly() { driver.get(pages.readOnlyPage); WebElement element = driver.findElement(By.id("readOnlyTextInput")); - Throwable t = catchThrowable(element::clear); - assertThat(t, instanceOf(InvalidElementStateException.class)); + assertThatExceptionOfType(InvalidElementStateException.class) + .isThrownBy(element::clear); } @Test @@ -64,23 +62,23 @@ public void testWritableTextAreaShouldClear() { driver.get(pages.readOnlyPage); WebElement element = driver.findElement(By.id("writableTextArea")); element.clear(); - assertEquals("", element.getAttribute("value")); + assertThat(element.getAttribute("value")).isEqualTo(""); } @Test public void testTextAreaShouldNotClearWhenDisabled() { driver.get(pages.readOnlyPage); WebElement element = driver.findElement(By.id("textAreaNotenabled")); - Throwable t = catchThrowable(element::clear); - assertThat(t, instanceOf(InvalidElementStateException.class)); + assertThatExceptionOfType(InvalidElementStateException.class) + .isThrownBy(element::clear); } @Test public void testTextAreaShouldNotClearWhenReadOnly() { driver.get(pages.readOnlyPage); WebElement element = driver.findElement(By.id("textAreaReadOnly")); - Throwable t = catchThrowable(element::clear); - assertThat(t, instanceOf(InvalidElementStateException.class)); + assertThatExceptionOfType(InvalidElementStateException.class) + .isThrownBy(element::clear); } @Test @@ -88,7 +86,7 @@ public void testContentEditableAreaShouldClear() { driver.get(pages.readOnlyPage); WebElement element = driver.findElement(By.id("content-editable")); element.clear(); - assertEquals("", element.getText()); + assertThat(element.getText()).isEqualTo(""); } @Test @@ -205,9 +203,9 @@ public void shouldBeAbleToClearWeekInput() { private void shouldBeAbleToClearInput(By locator, String oldValue) { driver.get(appServer.whereIs("inputs.html")); WebElement element = driver.findElement(locator); - assertEquals(oldValue, element.getAttribute("value")); + assertThat(element.getAttribute("value")).isEqualTo(oldValue); element.clear(); - assertEquals("", element.getAttribute("value")); + assertThat(element.getAttribute("value")).isEqualTo(""); } } diff --git a/java/client/test/org/openqa/selenium/ClickScrollingTest.java b/java/client/test/org/openqa/selenium/ClickScrollingTest.java index 012733a3b4467..1f24e4590c640 100644 --- a/java/client/test/org/openqa/selenium/ClickScrollingTest.java +++ b/java/client/test/org/openqa/selenium/ClickScrollingTest.java @@ -17,12 +17,8 @@ package org.openqa.selenium; -import static org.hamcrest.Matchers.greaterThan; -import static org.hamcrest.Matchers.instanceOf; -import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assume.assumeFalse; import static org.openqa.selenium.support.ui.ExpectedConditions.presenceOfElementLocated; import static org.openqa.selenium.support.ui.ExpectedConditions.titleIs; @@ -33,7 +29,6 @@ import static org.openqa.selenium.testing.Driver.IE; import static org.openqa.selenium.testing.Driver.MARIONETTE; import static org.openqa.selenium.testing.Driver.SAFARI; -import static org.openqa.selenium.testing.TestUtilities.catchThrowable; import org.junit.Test; import org.openqa.selenium.interactions.MoveTargetOutOfBoundsException; @@ -65,7 +60,7 @@ public void testClickingOnAnchorScrollsPage() { // Focusing on to click, but not actually following, // the link will scroll it in to view, which is a few pixels further than 0 - assertThat("Did not scroll", yOffset, is(greaterThan(300L))); + assertThat(yOffset).describedAs("Did not scroll").isGreaterThan(300L); } @Test @@ -84,7 +79,7 @@ public void testShouldBeAbleToClickOnAnElementHiddenByOverflow() { WebElement link = driver.findElement(By.id("line8")); // This used to throw a MoveTargetOutOfBoundsException - we don't expect it to link.click(); - assertEquals("line8", driver.findElement(By.id("clicked")).getText()); + assertThat(driver.findElement(By.id("clicked")).getText()).isEqualTo("line8"); } @Test @@ -122,7 +117,7 @@ public void testShouldNotScrollOverflowElementsWhichAreVisible() { item.click(); long yOffset = (Long)((JavascriptExecutor)driver).executeScript("return arguments[0].scrollTop;", list); - assertEquals("Should not have scrolled", 0, yOffset); + assertThat(yOffset).describedAs("Should not have scrolled").isEqualTo(0); } @Test @@ -133,7 +128,7 @@ public void testShouldNotScrollIfAlreadyScrolledAndElementIsInView() { driver.findElement(By.id("button1")).click(); long scrollTop = getScrollTop(); driver.findElement(By.id("button2")).click(); - assertEquals(scrollTop, getScrollTop()); + assertThat(getScrollTop()).isEqualTo(scrollTop); } @Test @@ -149,7 +144,7 @@ public void testShouldBeAbleToClickRadioButtonScrolledIntoView() { public void testShouldScrollOverflowElementsIfClickPointIsOutOfViewButElementIsInView() { driver.get(appServer.whereIs("scroll5.html")); driver.findElement(By.id("inner")).click(); - assertEquals("clicked", driver.findElement(By.id("clicked")).getText()); + assertThat(driver.findElement(By.id("clicked")).getText()).isEqualTo("clicked"); } @SwitchToTopAfterTest @@ -161,7 +156,7 @@ public void testShouldBeAbleToClickElementInAFrameThatIsOutOfView() { driver.switchTo().frame("frame"); WebElement element = driver.findElement(By.name("checkbox")); element.click(); - assertTrue(element.isSelected()); + assertThat(element.isSelected()).isTrue(); } @SwitchToTopAfterTest @@ -172,7 +167,7 @@ public void testShouldBeAbleToClickElementThatIsOutOfViewInAFrame() { driver.switchTo().frame("scrolling_frame"); WebElement element = driver.findElement(By.name("scroll_checkbox")); element.click(); - assertTrue(element.isSelected()); + assertThat(element.isSelected()).isTrue(); } @SwitchToTopAfterTest @@ -182,8 +177,7 @@ public void testShouldNotBeAbleToClickElementThatIsOutOfViewInANonScrollableFram driver.get(appServer.whereIs("scrolling_tests/page_with_non_scrolling_frame.html")); driver.switchTo().frame("scrolling_frame"); WebElement element = driver.findElement(By.name("scroll_checkbox")); - Throwable t = catchThrowable(element::click); - assertThat(t, instanceOf(MoveTargetOutOfBoundsException.class)); + assertThatExceptionOfType(MoveTargetOutOfBoundsException.class).isThrownBy(element::click); } @SwitchToTopAfterTest @@ -194,7 +188,7 @@ public void testShouldBeAbleToClickElementThatIsOutOfViewInAFrameThatIsOutOfView driver.switchTo().frame("scrolling_frame"); WebElement element = driver.findElement(By.name("scroll_checkbox")); element.click(); - assertTrue(element.isSelected()); + assertThat(element.isSelected()).isTrue(); } @SwitchToTopAfterTest @@ -206,7 +200,7 @@ public void testShouldBeAbleToClickElementThatIsOutOfViewInANestedFrame() { driver.switchTo().frame("nested_scrolling_frame"); WebElement element = driver.findElement(By.name("scroll_checkbox")); element.click(); - onlyPassIfNotOnMac(651, () -> assertTrue(element.isSelected())); + onlyPassIfNotOnMac(651, () -> assertThat(element.isSelected()).isTrue()); } @SwitchToTopAfterTest @@ -219,7 +213,7 @@ public void testShouldBeAbleToClickElementThatIsOutOfViewInANestedFrameThatIsOut WebElement element = driver.findElement(By.name("scroll_checkbox")); element.click(); - onlyPassIfNotOnMac(651, () -> assertTrue(element.isSelected())); + onlyPassIfNotOnMac(651, () -> assertThat(element.isSelected()).isTrue()); } private void onlyPassIfNotOnMac(int mozIssue, Runnable toCheck) { @@ -241,7 +235,7 @@ public void testShouldNotScrollWhenGettingElementSize() { driver.get(appServer.whereIs("scroll3.html")); long scrollTop = getScrollTop(); driver.findElement(By.id("button1")).getSize(); - assertEquals(scrollTop, getScrollTop()); + assertThat(getScrollTop()).isEqualTo(scrollTop); } private long getScrollTop() { @@ -258,6 +252,6 @@ public void testShouldBeAbleToClickElementInATallFrame() { driver.switchTo().frame("tall_frame"); WebElement element = driver.findElement(By.name("checkbox")); element.click(); - assertTrue(element.isSelected()); + assertThat(element.isSelected()).isTrue(); } } diff --git a/java/client/test/org/openqa/selenium/ClickTest.java b/java/client/test/org/openqa/selenium/ClickTest.java index d7b4a6190cb9b..33f47169e17c9 100644 --- a/java/client/test/org/openqa/selenium/ClickTest.java +++ b/java/client/test/org/openqa/selenium/ClickTest.java @@ -17,8 +17,7 @@ package org.openqa.selenium; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.fail; import static org.junit.Assume.assumeFalse; import static org.openqa.selenium.Platform.ANDROID; @@ -76,7 +75,7 @@ public void testCanClickOnAnAnchorAndNotReloadThePage() { Boolean samePage = (Boolean) ((JavascriptExecutor) driver) .executeScript("return document.latch"); - assertEquals("Latch was reset", Boolean.TRUE, samePage); + assertThat(samePage).as("Latch was reset").isTrue(); } @SwitchToTopAfterTest @@ -131,7 +130,7 @@ public void testCanClickOnAnElementWithTopSetToANegativeNumber() { driver.findElement(By.name("btn")).click(); String log = driver.findElement(By.id("log")).getText(); - assertEquals("click", log); + assertThat(log).isEqualTo("click"); } @Test @@ -144,7 +143,7 @@ public void testShouldSetRelatedTargetForMouseOver() { String log = driver.findElement(By.id("result")).getText(); - assertEquals("parent matches? true", log); + assertThat(log).isEqualTo("parent matches? true"); } @Test @@ -183,9 +182,7 @@ public void testClickingLabelShouldSetCheckbox() { driver.findElement(By.id("label-for-checkbox-with-label")).click(); - assertTrue( - "Should be selected", - driver.findElement(By.id("checkbox-with-label")).isSelected()); + assertThat(driver.findElement(By.id("checkbox-with-label")).isSelected()).isTrue(); } @Test diff --git a/java/client/test/org/openqa/selenium/ContentEditableTest.java b/java/client/test/org/openqa/selenium/ContentEditableTest.java index 8cc77f92eb86a..028d099250c1c 100644 --- a/java/client/test/org/openqa/selenium/ContentEditableTest.java +++ b/java/client/test/org/openqa/selenium/ContentEditableTest.java @@ -17,10 +17,7 @@ package org.openqa.selenium; -import static org.hamcrest.Matchers.anyOf; -import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assume.assumeFalse; import static org.openqa.selenium.testing.Driver.CHROME; import static org.openqa.selenium.testing.Driver.EDGE; @@ -56,12 +53,8 @@ public void testTypingIntoAnIFrameWithContentEditableOrDesignModeSet() { WebElement trusted = driver.findElement(By.id("istrusted")); WebElement id = driver.findElement(By.id("tagId")); - assertThat(trusted.getText(), anyOf( - equalTo("[true]"), - // Chrome does not set a trusted flag. - equalTo("[n/a]"), - equalTo("[]"))); - assertThat(id.getText(), anyOf(equalTo("[frameHtml]"), equalTo("[theBody]"))); + assertThat(trusted.getText()).isIn("[true]", "[n/a]", "[]"); + assertThat(id.getText()).isIn("[frameHtml]", "[theBody]"); } @Test @@ -79,7 +72,7 @@ public void testNonPrintableCharactersShouldWorkWithContentEditableOrDesignModeS element.sendKeys("Dishy", Keys.BACK_SPACE, Keys.LEFT, Keys.LEFT); element.sendKeys(Keys.LEFT, Keys.LEFT, "F", Keys.DELETE, Keys.END, "ee!"); - assertEquals("Fishee!", element.getText()); + assertThat(element.getText()).isEqualTo("Fishee!"); } @Test @@ -89,7 +82,7 @@ public void testShouldBeAbleToTypeIntoEmptyContentEditableElement() { editable.sendKeys("cheese"); - assertThat(editable.getText(), equalTo("cheese")); + assertThat(editable.getText()).isEqualTo("cheese"); } @Test @@ -104,7 +97,7 @@ public void testShouldBeAbleToTypeIntoContentEditableElementWithExistingValue() String initialText = editable.getText(); editable.sendKeys(", edited"); - assertThat(editable.getText(), equalTo(initialText + ", edited")); + assertThat(editable.getText()).isEqualTo(initialText + ", edited"); } @Test @@ -118,7 +111,7 @@ public void testShouldBeAbleToTypeIntoTinyMCE() { editable.clear(); editable.sendKeys("cheese"); // requires focus on OS X - assertThat(editable.getText(), equalTo("cheese")); + assertThat(editable.getText()).isEqualTo("cheese"); } @Test @@ -134,7 +127,7 @@ public void testShouldAppendToTinyMCE() { editable.sendKeys(" and cheese"); // requires focus on OS X - assertThat(editable.getText(), equalTo("Initial content and cheese")); + assertThat(editable.getText()).isEqualTo("Initial content and cheese"); } @Test @@ -146,8 +139,7 @@ public void appendsTextToEndOfContentEditableWithMultipleTextNodes() { driver.get(appServer.whereIs("content-editable.html")); WebElement input = driver.findElement(By.id("editable")); input.sendKeys(", world!"); - System.out.println("input.getText() = " + input.getText()); - assertEquals("Why hello, world!", input.getText()); + assertThat(input.getText()).isEqualTo("Why hello, world!"); } } diff --git a/java/client/test/org/openqa/selenium/CookieImplementationTest.java b/java/client/test/org/openqa/selenium/CookieImplementationTest.java index 06c70689ce3f2..c125bd40d99d3 100644 --- a/java/client/test/org/openqa/selenium/CookieImplementationTest.java +++ b/java/client/test/org/openqa/selenium/CookieImplementationTest.java @@ -17,15 +17,7 @@ package org.openqa.selenium; -import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.not; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNotSame; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assume.assumeTrue; import static org.openqa.selenium.testing.Driver.ALL; import static org.openqa.selenium.testing.Driver.CHROME; @@ -85,14 +77,14 @@ public void testShouldGetCookieByName() { addCookieOnServerSide(new Cookie(key, value)); Cookie cookie = driver.manage().getCookieNamed(key); - assertEquals(value, cookie.getValue()); + assertThat(cookie.getValue()).isEqualTo(value); } @Test public void testShouldBeAbleToAddCookie() { String key = generateUniqueKey(); String value = "foo"; - Cookie cookie = new Cookie.Builder(key, value).build(); + Cookie cookie = new Cookie.Builder(key, value).domain("comp1").build(); assertCookieIsNotPresentWithName(key); driver.manage().addCookie(cookie); @@ -122,10 +114,10 @@ public void testGetAllCookies() { openAnotherPage(); cookies = driver.manage().getCookies(); - assertEquals(countBefore + 2, cookies.size()); + assertThat(cookies.size()).isEqualTo(countBefore + 2); - assertTrue(cookies.contains(one)); - assertTrue(cookies.contains(two)); + assertThat(cookies.contains(one)).isTrue(); + assertThat(cookies.contains(two)).isTrue(); } @Test @@ -178,8 +170,8 @@ public void testShouldNotDeleteCookiesWithASimilarName() { options.deleteCookieNamed(cookieOneName); Set cookies = options.getCookies(); - assertFalse(cookies.toString(), cookies.contains(cookie1)); - assertTrue(cookies.toString(), cookies.contains(cookie2)); + assertThat(cookies).doesNotContain(cookie1); + assertThat(cookies).contains(cookie2); } @Test @@ -224,7 +216,7 @@ public void testCannotGetCookiesWithPathDifferingOnlyInCase() { driver.manage().addCookie(cookie); driver.get(domainHelper.getUrlForFirstValidHostname("/common/animals")); - assertNull(driver.manage().getCookieNamed(cookieName)); + assertThat(driver.manage().getCookieNamed(cookieName)).isNull(); } @Test @@ -288,7 +280,7 @@ public void testShouldBeAbleToSetDomainToTheCurrentDomain() throws Exception { driver.get(domainHelper.getUrlForFirstValidHostname("javascriptPage.html")); Set cookies = driver.manage().getCookies(); - assertTrue(cookies.contains(cookie)); + assertThat(cookies).contains(cookie); } @Test @@ -307,12 +299,12 @@ public void testShouldWalkThePathToDeleteACookie() { driver.get(domainHelper.getUrlForFirstValidHostname("child/grandchild/grandchildPage.html")); driver.manage().deleteCookieNamed("rodent"); - assertNull(driver.manage().getCookies().toString(), driver.manage().getCookieNamed("rodent")); + assertThat(driver.manage().getCookieNamed("rodent")).isNull(); Set cookies = driver.manage().getCookies(); - assertEquals(2, cookies.size()); - assertTrue(cookies.contains(cookie1)); - assertTrue(cookies.contains(cookie3)); + assertThat(cookies).hasSize(2); + assertThat(cookies).contains(cookie1); + assertThat(cookies).contains(cookie3); driver.manage().deleteAllCookies(); driver.get(domainHelper.getUrlForFirstValidHostname("child/grandchild/grandchildPage.html")); @@ -355,9 +347,9 @@ public void testCookieEqualityAfterSetAndGet() { } } - assertNotNull("Cookie was null", retrievedCookie); + assertThat(retrievedCookie).isNotNull(); // Cookie.equals only compares name, domain and path - assertEquals(addedCookie, retrievedCookie); + assertThat(retrievedCookie).isEqualTo(addedCookie); } @Test @@ -370,8 +362,8 @@ public void testRetainsCookieExpiry() { driver.manage().addCookie(addedCookie); Cookie retrieved = driver.manage().getCookieNamed("fish"); - assertNotNull(retrieved); - assertEquals(addedCookie.getExpiry(), retrieved.getExpiry()); + assertThat(retrieved).isNotNull(); + assertThat(retrieved.getExpiry()).isEqualTo(addedCookie.getExpiry()); } @Test @@ -390,7 +382,7 @@ public void canHandleSecureCookie() { driver.navigate().refresh(); Cookie retrieved = driver.manage().getCookieNamed("fish"); - assertNotNull(retrieved); + assertThat(retrieved).isNotNull(); } @Test @@ -409,8 +401,8 @@ public void testRetainsCookieSecure() { driver.navigate().refresh(); Cookie retrieved = driver.manage().getCookieNamed("fish"); - assertNotNull(retrieved); - assertTrue(retrieved.isSecure()); + assertThat(retrieved).isNotNull(); + assertThat(retrieved.isSecure()).isTrue(); } @Test @@ -426,7 +418,7 @@ public void canHandleHttpOnlyCookie() { driver.get(domainHelper.getUrlForFirstValidHostname("animals")); Cookie retrieved = driver.manage().getCookieNamed("fish"); - assertNotNull(retrieved); + assertThat(retrieved).isNotNull(); } @Test @@ -443,8 +435,8 @@ public void testRetainsHttpOnlyFlag() { driver.get(domainHelper.getUrlForFirstValidHostname("animals")); Cookie retrieved = driver.manage().getCookieNamed("fish"); - assertNotNull(retrieved); - assertTrue(retrieved.isHttpOnly()); + assertThat(retrieved).isNotNull(); + assertThat(retrieved.isHttpOnly()).isTrue(); } @Test @@ -454,8 +446,7 @@ public void testSettingACookieThatExpiredInThePast() { driver.manage().addCookie(cookie); cookie = driver.manage().getCookieNamed("fish"); - assertNull( - "Cookie expired before it was set, so nothing should be returned: " + cookie, cookie); + assertThat(cookie).as("Cookie expired before it was set, so nothing should be returned").isNull(); } @Test @@ -492,14 +483,13 @@ public void testShouldDeleteOneOfTheCookiesWithTheSameName() { WebDriver.Options options = driver.manage(); options.addCookie(cookie1); options.addCookie(cookie2); - assertEquals(driver.manage().getCookies().size(), 2); + assertThat(driver.manage().getCookies()).hasSize(2); driver.manage().deleteCookie(cookie1); - assertEquals(driver.manage().getCookies().size(), 1); + assertThat(driver.manage().getCookies()).hasSize(1); Cookie retrieved = driver.manage().getCookieNamed("fish"); - assertNotNull("Cookie was null", retrieved); - assertEquals(cookie2, retrieved); + assertThat(retrieved).isEqualTo(cookie2); } private String generateUniqueKey() { @@ -507,53 +497,46 @@ private String generateUniqueKey() { } private void assertNoCookiesArePresent() { - Set cookies = driver.manage().getCookies(); - assertTrue("Cookies were not empty, present: " + cookies, - cookies.isEmpty()); + assertThat(driver.manage().getCookies()).isEmpty(); String documentCookie = getDocumentCookieOrNull(); if (documentCookie != null) { - assertEquals("Cookies were not empty", "", documentCookie); + assertThat(documentCookie).isEqualTo(""); } } private void assertSomeCookiesArePresent() { - assertFalse("Cookies were empty", - driver.manage().getCookies().isEmpty()); + assertThat(driver.manage().getCookies()).isNotEmpty(); String documentCookie = getDocumentCookieOrNull(); if (documentCookie != null) { - assertNotSame("Cookies were empty", "", documentCookie); + assertThat(documentCookie).as("Cookies were empty").isNotEqualTo(""); } } private void assertCookieIsNotPresentWithName(final String key) { - assertNull("Cookie was present with name " + key, driver.manage().getCookieNamed(key)); + assertThat(driver.manage().getCookieNamed(key)).as("Cookie with name " + key).isNull(); String documentCookie = getDocumentCookieOrNull(); if (documentCookie != null) { - assertThat("Cookie was present with name " + key, - documentCookie, - not(containsString(key + "="))); + assertThat(documentCookie).as("Cookie with name " + key).doesNotContain((key + "=")); } } private void assertCookieIsPresentWithName(final String key) { - assertNotNull("Cookie was not present with name " + key, driver.manage().getCookieNamed(key)); + assertThat(driver.manage().getCookieNamed(key)).as("Cookie with name " + key).isNotNull(); String documentCookie = getDocumentCookieOrNull(); if (documentCookie != null) { - assertThat("Cookie was not present with name " + key + ", got: " + documentCookie, - documentCookie, - containsString(key + "=")); + assertThat(documentCookie) + .as("Cookie was not present with name " + key + ", got: " + documentCookie) + .contains(key + "="); } } private void assertCookieHasValue(final String key, final String value) { - assertEquals("Cookie had wrong value", - value, - driver.manage().getCookieNamed(key).getValue()); + assertThat(driver.manage().getCookieNamed(key).getValue()).isEqualTo(value); String documentCookie = getDocumentCookieOrNull(); if (documentCookie != null) { - assertThat("Cookie was present with name " + key, - documentCookie, - containsString(key + "=" + value)); + assertThat(documentCookie) + .as("Cookie was present with name " + key) + .contains(key + "=" + value); } } diff --git a/java/client/test/org/openqa/selenium/CookieTest.java b/java/client/test/org/openqa/selenium/CookieTest.java index 296ad56f23a6d..4e8ca5ecc5562 100644 --- a/java/client/test/org/openqa/selenium/CookieTest.java +++ b/java/client/test/org/openqa/selenium/CookieTest.java @@ -17,16 +17,10 @@ package org.openqa.selenium; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.instanceOf; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; -import static org.openqa.selenium.testing.TestUtilities.catchThrowable; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; @@ -35,7 +29,6 @@ import java.io.ObjectOutputStream; import java.util.Date; -@RunWith(JUnit4.class) public class CookieTest { @Test @@ -46,39 +39,39 @@ public void testCanCreateAWellFormedCookie() { @Test public void testShouldThrowAnExceptionWhenSemiColonExistsInTheCookieAttribute() { Cookie cookie = new Cookie("hi;hi", "value", null, null, null, false); - Throwable t = catchThrowable(cookie::validate); - assertThat(t, instanceOf(IllegalArgumentException.class)); + assertThatExceptionOfType(IllegalArgumentException.class) + .isThrownBy(cookie::validate); } @Test public void testShouldThrowAnExceptionTheNameIsNull() { Cookie cookie = new Cookie(null, "value", null, null, null, false); - Throwable t = catchThrowable(cookie::validate); - assertThat(t, instanceOf(IllegalArgumentException.class)); + assertThatExceptionOfType(IllegalArgumentException.class) + .isThrownBy(cookie::validate); } @Test public void testCookiesShouldAllowSecureToBeSet() { Cookie cookie = new Cookie("name", "value", "", "/", new Date(), true); - assertTrue(cookie.isSecure()); + assertThat(cookie.isSecure()).isTrue(); } @Test public void testSecureDefaultsToFalse() { Cookie cookie = new Cookie("name", "value"); - assertFalse(cookie.isSecure()); + assertThat(cookie.isSecure()).isFalse(); } @Test public void testCookiesShouldAllowHttpOnlyToBeSet() { Cookie cookie = new Cookie("name", "value", "", "/", new Date(), false, true); - assertTrue(cookie.isHttpOnly()); + assertThat(cookie.isHttpOnly()).isTrue(); } @Test public void testHttpOnlyDefaultsToFalse() { Cookie cookie = new Cookie("name", "value"); - assertFalse(cookie.isHttpOnly()); + assertThat(cookie.isHttpOnly()).isFalse(); } @Test @@ -93,6 +86,6 @@ public void testCookieSerializes() throws IOException, ClassNotFoundException { ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(serializedCookie); ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream); Cookie deserializedCookie = (Cookie) objectInputStream.readObject(); - assertThat(cookieToSerialize, equalTo(deserializedCookie)); + assertThat(cookieToSerialize).isEqualTo(deserializedCookie); } } diff --git a/java/client/test/org/openqa/selenium/CorrectEventFiringTest.java b/java/client/test/org/openqa/selenium/CorrectEventFiringTest.java index c4e4b6f03dea4..e710880d73937 100644 --- a/java/client/test/org/openqa/selenium/CorrectEventFiringTest.java +++ b/java/client/test/org/openqa/selenium/CorrectEventFiringTest.java @@ -17,17 +17,8 @@ package org.openqa.selenium; -import static org.hamcrest.Matchers.anyOf; -import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.instanceOf; -import static org.hamcrest.Matchers.not; -import static org.hamcrest.Matchers.startsWith; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assert.fail; import static org.junit.Assume.assumeFalse; import static org.openqa.selenium.WaitingConditions.elementTextToContain; @@ -40,7 +31,6 @@ import static org.openqa.selenium.testing.Driver.IE; import static org.openqa.selenium.testing.Driver.MARIONETTE; import static org.openqa.selenium.testing.Driver.SAFARI; -import static org.openqa.selenium.testing.TestUtilities.catchThrowable; import static org.openqa.selenium.testing.TestUtilities.isOldIe; import org.junit.Test; @@ -170,8 +160,8 @@ public void testShouldFireEventsInTheRightOrder() { for (String event : new String[] {"mousedown", "focus", "mouseup", "click"}) { int index = text.indexOf(event); - assertTrue(event + " did not fire at all", index != -1); - assertTrue(event + " did not fire in the correct order", index > lastIndex); + assertThat(index).as(event + " did not fire at all").isNotEqualTo(-1); + assertThat(index).as(event + " did not fire in the correct order").isGreaterThan(lastIndex); lastIndex = index; } } @@ -184,7 +174,7 @@ public void testsShouldIssueMouseDownEvents() { assertEventFired("mouse down", driver); String result = driver.findElement(By.id("result")).getText(); - assertThat(result, equalTo("mouse down")); + assertThat(result).isEqualTo("mouse down"); } @Test @@ -195,7 +185,7 @@ public void testShouldIssueClickEvents() { WebElement result = driver.findElement(By.id("result")); wait.until(elementTextToEqual(result, "mouse click")); - assertThat(result.getText(), equalTo("mouse click")); + assertThat(result.getText()).isEqualTo("mouse click"); } @Test @@ -206,7 +196,7 @@ public void testShouldIssueMouseUpEvents() { WebElement result = driver.findElement(By.id("result")); wait.until(elementTextToEqual(result, "mouse up")); - assertThat(result.getText(), equalTo("mouse up")); + assertThat(result.getText()).isEqualTo("mouse up"); } @Test @@ -217,7 +207,7 @@ public void testMouseEventsShouldBubbleUpToContainingElements() { WebElement result = driver.findElement(By.id("result")); wait.until(elementTextToEqual(result, "mouse down")); - assertThat(result.getText(), equalTo("mouse down")); + assertThat(result.getText()).isEqualTo("mouse down"); } @Test @@ -234,9 +224,9 @@ public void testShouldEmitOnChangeEventsWhenSelectingElements() { WebElement bar = allOptions.get(1); foo.click(); - assertThat(driver.findElement(By.id("result")).getText(), equalTo(initialTextValue)); + assertThat(driver.findElement(By.id("result")).getText()).isEqualTo(initialTextValue); bar.click(); - assertThat(driver.findElement(By.id("result")).getText(), equalTo("bar")); + assertThat(driver.findElement(By.id("result")).getText()).isEqualTo("bar"); } @Test @@ -250,9 +240,9 @@ public void testShouldEmitOnClickEventsWhenSelectingElements() { WebElement bar = allOptions.get(1); foo.click(); - assertThat(driver.findElement(By.id("result")).getText(), equalTo("foo")); + assertThat(driver.findElement(By.id("result")).getText()).isEqualTo("foo"); bar.click(); - assertThat(driver.findElement(By.id("result")).getText(), equalTo("bar")); + assertThat(driver.findElement(By.id("result")).getText()).isEqualTo("bar"); } @Test @@ -275,7 +265,7 @@ public void testShouldEmitClickEventWhenClickingOnATextInputElement() { clicker.click(); wait.until(elementValueToEqual(clicker, "Clicked")); - assertThat(clicker.getAttribute("value"), equalTo("Clicked")); + assertThat(clicker.getAttribute("value")).isEqualTo("Clicked"); } @Test @@ -285,7 +275,7 @@ public void testShouldFireTwoClickEventsWhenClickingOnALabel() { driver.findElement(By.id("labelForCheckbox")).click(); WebElement result = driver.findElement(By.id("result")); - assertNotNull(wait.until(elementTextToContain(result, "labelclick chboxclick"))); + assertThat(wait.until(elementTextToContain(result, "labelclick chboxclick"))).isNotNull(); } @Test @@ -297,7 +287,7 @@ public void testClearingAnElementShouldCauseTheOnChangeHandlerToFire() { element.clear(); WebElement result = driver.findElement(By.id("result")); - assertThat(result.getText(), equalTo("Cleared")); + assertThat(result.getText()).isEqualTo("Cleared"); } @Test @@ -400,8 +390,7 @@ public void testClickingAnUnfocusableChildShouldNotBlurTheParent() { assertEventNotFired("blur", driver); // Click on child. It is not focusable, so focus should stay on the parent. driver.findElement(By.id("hideOnBlurChild")).click(); - assertTrue("#hideOnBlur should still be displayed after click", - parent.isDisplayed()); + assertThat(parent.isDisplayed()).as("#hideOnBlur should still be displayed after click").isTrue(); assertEventNotFired("blur", driver); // Click elsewhere, and let the element disappear. driver.findElement(By.id("result")).click(); @@ -441,7 +430,7 @@ public void testUploadingFileShouldFireOnChangeEvent() throws IOException { driver.get(pages.formPage); WebElement uploadElement = driver.findElement(By.id("upload")); WebElement result = driver.findElement(By.id("fileResults")); - assertThat(result.getText(), equalTo("")); + assertThat(result.getText()).isEqualTo(""); File file = File.createTempFile("test", "txt"); file.deleteOnExit(); @@ -450,7 +439,7 @@ public void testUploadingFileShouldFireOnChangeEvent() throws IOException { // Shift focus to something else because send key doesn't make the focus leave driver.findElement(By.id("id-name1")).click(); - assertThat(result.getText(), equalTo("changed")); + assertThat(result.getText()).isEqualTo("changed"); } private String getTextFromElementOnceAvailable(String elementId) { @@ -470,8 +459,8 @@ public void testShouldReportTheXAndYCoordinatesWhenClicking() { String clientX = getTextFromElementOnceAvailable("clientX"); String clientY = getTextFromElementOnceAvailable("clientY"); - assertThat(clientX, not(equalTo("0"))); - assertThat(clientY, not(equalTo("0"))); + assertThat(clientX).isNotEqualTo("0"); + assertThat(clientY).isNotEqualTo("0"); } @Test @@ -479,7 +468,7 @@ public void testClickEventsShouldBubble() { driver.get(pages.clicksPage); driver.findElement(By.id("bubblesFrom")).click(); boolean eventBubbled = (Boolean)((JavascriptExecutor)driver).executeScript("return !!window.bubbledClick;"); - assertTrue("Event didn't bubble up", eventBubbled); + assertThat(eventBubbled).as("Event bubbled").isTrue(); } @Test @@ -490,10 +479,8 @@ public void testClickOverlappingElements() { assumeFalse(isOldIe(driver)); driver.get(appServer.whereIs("click_tests/overlapping_elements.html")); WebElement element = driver.findElement(By.id("under")); - Throwable t = catchThrowable(element::click); - assertThat(t, instanceOf(WebDriverException.class)); - assertThat(t.getMessage(), anyOf(containsString("Other element would receive the click"), - containsString("is not clickable at point"))); + assertThatExceptionOfType(ElementClickInterceptedException.class) + .isThrownBy(element::click); } @Test @@ -509,8 +496,8 @@ public void testClickPartiallyOverlappingElements() { WebElement over = driver.findElement(By.id("over" + i)); ((JavascriptExecutor) driver).executeScript("arguments[0].style.display = 'none'", over); driver.findElement(By.id("under")).click(); - assertEquals(driver.findElement(By.id("log")).getText(), - "Log:\n" + assertThat(driver.findElement(By.id("log")).getText()) + .isEqualTo("Log:\n" + "mousedown in under (handled by under)\n" + "mousedown in under (handled by body)\n" + "mouseup in under (handled by under)\n" @@ -531,8 +518,8 @@ public void testNativelyClickOverlappingElements() { assumeFalse(isOldIe(driver)); driver.get(appServer.whereIs("click_tests/overlapping_elements.html")); driver.findElement(By.id("under")).click(); - assertEquals(driver.findElement(By.id("log")).getText(), - "Log:\n" + assertThat(driver.findElement(By.id("log")).getText()) + .isEqualTo("Log:\n" + "mousedown in over (handled by over)\n" + "mousedown in over (handled by body)\n" + "mouseup in over (handled by over)\n" @@ -548,12 +535,12 @@ public void testClickAnElementThatDisappear() { assumeFalse(isOldIe(driver)); driver.get(appServer.whereIs("click_tests/disappearing_element.html")); driver.findElement(By.id("over")).click(); - assertThat(driver.findElement(By.id("log")).getText(), - startsWith("Log:\n" - + "mousedown in over (handled by over)\n" - + "mousedown in over (handled by body)\n" - + "mouseup in under (handled by under)\n" - + "mouseup in under (handled by body)")); + assertThat(driver.findElement(By.id("log")).getText()) + .startsWith("Log:\n" + + "mousedown in over (handled by over)\n" + + "mousedown in over (handled by body)\n" + + "mouseup in under (handled by under)\n" + + "mouseup in under (handled by body)"); } private static void clickOnElementWhichRecordsEvents(WebDriver driver) { @@ -566,13 +553,13 @@ private static void assertEventFired(String eventName, WebDriver driver) { String text = new WebDriverWait(driver, 10).until(elementTextToContain(result, eventName)); boolean conditionMet = text.contains(eventName); - assertTrue("No " + eventName + " fired: " + text, conditionMet); + assertThat(conditionMet).as("%s fired with text %s", eventName, text).isTrue(); } private static void assertEventNotFired(String eventName, WebDriver driver) { WebElement result = driver.findElement(By.id("result")); String text = result.getText(); - assertFalse(eventName + " fired: " + text, text.contains(eventName)); + assertThat(text).as("%s fired with text %s").doesNotContain(eventName); } private static boolean browserNeedsFocusOnThisOs(WebDriver driver) { diff --git a/java/client/test/org/openqa/selenium/CssValueTest.java b/java/client/test/org/openqa/selenium/CssValueTest.java index 9346f330a89c5..72321183bc4d6 100644 --- a/java/client/test/org/openqa/selenium/CssValueTest.java +++ b/java/client/test/org/openqa/selenium/CssValueTest.java @@ -17,10 +17,7 @@ package org.openqa.selenium; -import static org.hamcrest.Matchers.anyOf; -import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; import org.openqa.selenium.support.Color; @@ -35,12 +32,12 @@ public void testShouldPickUpStyleOfAnElement() { WebElement element = driver.findElement(By.id("green-parent")); Color backgroundColour = Color.fromString(element.getCssValue("background-color")); - assertEquals(new Color(0, 128, 0, 1), backgroundColour); + assertThat(backgroundColour).isEqualTo(new Color(0, 128, 0, 1)); element = driver.findElement(By.id("red-item")); backgroundColour = Color.fromString(element.getCssValue("background-color")); - assertEquals(new Color(255, 0, 0, 1), backgroundColour); + assertThat(backgroundColour).isEqualTo(new Color(255, 0, 0, 1)); } @Test @@ -49,11 +46,11 @@ public void testGetCssValueShouldReturnStandardizedColour() { WebElement element = driver.findElement(By.id("namedColor")); Color backgroundColour = Color.fromString(element.getCssValue("background-color")); - assertEquals(new Color(0, 128, 0, 1), backgroundColour); + assertThat(backgroundColour).isEqualTo(new Color(0, 128, 0, 1)); element = driver.findElement(By.id("rgb")); backgroundColour = Color.fromString(element.getCssValue("background-color")); - assertEquals(new Color(0, 128, 0, 1), backgroundColour); + assertThat(backgroundColour).isEqualTo(new Color(0, 128, 0, 1)); } @Test @@ -64,9 +61,7 @@ public void testShouldAllowInheritedStylesToBeUsed() { String backgroundColour = element.getCssValue("background-color"); // TODO: How should this be standardized? Should it be standardized? - assertThat(backgroundColour, anyOf( - equalTo("transparent"), - equalTo("rgba(0, 0, 0, 0)"))); + assertThat(backgroundColour).isIn("transparent", "rgba(0, 0, 0, 0)"); } } diff --git a/java/client/test/org/openqa/selenium/DimensionTest.java b/java/client/test/org/openqa/selenium/DimensionTest.java index b38448c9880c5..7bf49187d61f3 100644 --- a/java/client/test/org/openqa/selenium/DimensionTest.java +++ b/java/client/test/org/openqa/selenium/DimensionTest.java @@ -17,23 +17,19 @@ package org.openqa.selenium; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotSame; +import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; /** * Test WebDriver's Dimensions class. */ -@RunWith(JUnit4.class) public class DimensionTest { @Test public void testSimpleAssignment() { Dimension d1 = new Dimension(100, 200); - assertEquals(200, d1.getHeight()); - assertEquals(100, d1.getWidth()); + assertThat(d1.getHeight()).isEqualTo(200); + assertThat(d1.getWidth()).isEqualTo(100); } @Test @@ -41,14 +37,14 @@ public void testEquality() { Dimension d1 = new Dimension(100, 200); Dimension d2 = new Dimension(200, 200); - assertNotSame(d1, d2); + assertThat(d1).isNotSameAs(d2); // Doesn't have to be different, but known to be different for this case. - assertNotSame(d1.hashCode(), d2.hashCode()); + assertThat(d1.hashCode()).isNotEqualTo(d2.hashCode()); Dimension d1copy = new Dimension(100, 200); - assertEquals(d1, d1copy); - assertEquals(d1.hashCode(), d1copy.hashCode()); + assertThat(d1copy).isEqualTo(d1); + assertThat(d1copy.hashCode()).isEqualTo(d1.hashCode()); } } diff --git a/java/client/test/org/openqa/selenium/ElementAttributeTest.java b/java/client/test/org/openqa/selenium/ElementAttributeTest.java index d177c727a7a5d..356959b6ba201 100644 --- a/java/client/test/org/openqa/selenium/ElementAttributeTest.java +++ b/java/client/test/org/openqa/selenium/ElementAttributeTest.java @@ -17,21 +17,10 @@ package org.openqa.selenium; -import static org.hamcrest.Matchers.anyOf; -import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.instanceOf; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.nullValue; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assume.assumeFalse; import static org.openqa.selenium.testing.Driver.SAFARI; -import static org.openqa.selenium.testing.TestUtilities.catchThrowable; import org.junit.Test; import org.openqa.selenium.support.ui.ExpectedConditions; @@ -48,7 +37,7 @@ public void testShouldReturnNullWhenGettingTheValueOfAnAttributeThatIsNotListed( driver.get(pages.simpleTestPage); WebElement head = driver.findElement(By.xpath("/html")); String attribute = head.getAttribute("cheese"); - assertThat(attribute, is(nullValue())); + assertThat(attribute).isNull(); } @Test @@ -56,7 +45,7 @@ public void testShouldReturnNullWhenGettingSrcAttributeOfInvalidImgTag() { driver.get(pages.simpleTestPage); WebElement img = driver.findElement(By.id("invalidImgTag")); String attribute = img.getAttribute("src"); - assertThat(attribute, is(nullValue())); + assertThat(attribute).isNull(); } @Test @@ -64,7 +53,7 @@ public void testShouldReturnAnAbsoluteUrlWhenGettingSrcAttributeOfAValidImgTag() driver.get(pages.simpleTestPage); WebElement img = driver.findElement(By.id("validImgTag")); String attribute = img.getAttribute("src"); - assertThat(attribute, equalTo(appServer.whereIs("icon.gif"))); + assertThat(attribute).isEqualTo(appServer.whereIs("icon.gif")); } @Test @@ -72,26 +61,26 @@ public void testShouldReturnAnAbsoluteUrlWhenGettingHrefAttributeOfAValidAnchorT driver.get(pages.simpleTestPage); WebElement img = driver.findElement(By.id("validAnchorTag")); String attribute = img.getAttribute("href"); - assertThat(attribute, equalTo(appServer.whereIs("icon.gif"))); + assertThat(attribute).isEqualTo(appServer.whereIs("icon.gif")); } @Test public void testShouldReturnEmptyAttributeValuesWhenPresentAndTheValueIsActuallyEmpty() { driver.get(pages.simpleTestPage); WebElement body = driver.findElement(By.xpath("//body")); - assertThat(body.getAttribute("style"), equalTo("")); + assertThat(body.getAttribute("style")).isEqualTo(""); } @Test public void testShouldReturnTheValueOfTheDisabledAttributeAsNullIfNotSet() { driver.get(pages.formPage); WebElement inputElement = driver.findElement(By.xpath("//input[@id='working']")); - assertThat(inputElement.getAttribute("disabled"), equalTo(null)); - assertThat(inputElement.isEnabled(), equalTo(true)); + assertThat(inputElement.getAttribute("disabled")).isNull(); + assertThat(inputElement.isEnabled()).isTrue(); WebElement pElement = driver.findElement(By.id("peas")); - assertThat(pElement.getAttribute("disabled"), equalTo(null)); - assertThat(pElement.isEnabled(), equalTo(true)); + assertThat(pElement.getAttribute("disabled")).isNull(); + assertThat(pElement.isEnabled()).isTrue(); } @Test @@ -100,30 +89,30 @@ public void testShouldReturnTheValueOfTheIndexAttrbuteEvenIfItIsMissing() { WebElement multiSelect = driver.findElement(By.id("multi")); List options = multiSelect.findElements(By.tagName("option")); - assertThat(options.get(1).getAttribute("index"), equalTo("1")); + assertThat(options.get(1).getAttribute("index")).isEqualTo("1"); } @Test public void testShouldIndicateTheElementsThatAreDisabledAreNotEnabled() { driver.get(pages.formPage); WebElement inputElement = driver.findElement(By.xpath("//input[@id='notWorking']")); - assertThat(inputElement.isEnabled(), is(false)); + assertThat(inputElement.isEnabled()).isFalse(); inputElement = driver.findElement(By.xpath("//input[@id='working']")); - assertThat(inputElement.isEnabled(), is(true)); + assertThat(inputElement.isEnabled()).isTrue(); } @Test public void testElementsShouldBeDisabledIfTheyAreDisabledUsingRandomDisabledStrings() { driver.get(pages.formPage); WebElement disabledTextElement1 = driver.findElement(By.id("disabledTextElement1")); - assertThat(disabledTextElement1.isEnabled(), is(false)); + assertThat(disabledTextElement1.isEnabled()).isFalse(); WebElement disabledTextElement2 = driver.findElement(By.id("disabledTextElement2")); - assertThat(disabledTextElement2.isEnabled(), is(false)); + assertThat(disabledTextElement2.isEnabled()).isFalse(); WebElement disabledSubmitElement = driver.findElement(By.id("disabledSubmitElement")); - assertThat(disabledSubmitElement.isEnabled(), is(false)); + assertThat(disabledSubmitElement.isEnabled()).isFalse(); } @Test @@ -131,21 +120,21 @@ public void testElementsShouldBeDisabledIfTheyAreDisabledUsingRandomDisabledStri public void testShouldThrowExceptionIfSendingKeysToElementDisabledUsingRandomDisabledStrings() { driver.get(pages.formPage); WebElement disabledTextElement1 = driver.findElement(By.id("disabledTextElement1")); - Throwable t = catchThrowable(() -> disabledTextElement1.sendKeys("foo")); - assertThat(t, instanceOf(InvalidElementStateException.class)); - assertThat(disabledTextElement1.getText(), is("")); + assertThatExceptionOfType(InvalidElementStateException.class) + .isThrownBy(() -> disabledTextElement1.sendKeys("foo")); + assertThat(disabledTextElement1.getText()).isEqualTo(""); WebElement disabledTextElement2 = driver.findElement(By.id("disabledTextElement2")); - Throwable t2 = catchThrowable(() -> disabledTextElement2.sendKeys("bar")); - assertThat(t2, instanceOf(InvalidElementStateException.class)); - assertThat(disabledTextElement2.getText(), is("")); + assertThatExceptionOfType(InvalidElementStateException.class) + .isThrownBy(() -> disabledTextElement2.sendKeys("bar")); + assertThat(disabledTextElement2.getText()).isEqualTo(""); } @Test public void testShouldIndicateWhenATextAreaIsDisabled() { driver.get(pages.formPage); WebElement textArea = driver.findElement(By.xpath("//textarea[@id='notWorkingArea']")); - assertThat(textArea.isEnabled(), is(false)); + assertThat(textArea.isEnabled()).isFalse(); } @Test @@ -155,17 +144,17 @@ public void testShouldIndicateWhenASelectIsDisabled() { WebElement enabled = driver.findElement(By.name("selectomatic")); WebElement disabled = driver.findElement(By.name("no-select")); - assertTrue(enabled.isEnabled()); - assertFalse(disabled.isEnabled()); + assertThat(enabled.isEnabled()).isTrue(); + assertThat(disabled.isEnabled()).isFalse(); } @Test public void testShouldReturnTheValueOfCheckedForACheckboxOnlyIfItIsChecked() { driver.get(pages.formPage); WebElement checkbox = driver.findElement(By.xpath("//input[@id='checky']")); - assertThat(checkbox.getAttribute("checked"), equalTo(null)); + assertThat(checkbox.getAttribute("checked")).isNull(); checkbox.click(); - assertThat(checkbox.getAttribute("checked"), equalTo("true")); + assertThat(checkbox.getAttribute("checked")).isEqualTo("true"); } @Test @@ -175,14 +164,14 @@ public void testShouldOnlyReturnTheValueOfSelectedForRadioButtonsIfItIsSet() { WebElement initiallyNotSelected = driver.findElement(By.id("peas")); WebElement initiallySelected = driver.findElement(By.id("cheese_and_peas")); - assertThat(neverSelected.getAttribute("selected"), equalTo(null)); - assertThat(initiallyNotSelected.getAttribute("selected"), equalTo(null)); - assertThat(initiallySelected.getAttribute("selected"), equalTo("true")); + assertThat(neverSelected.getAttribute("selected")).isNull(); + assertThat(initiallyNotSelected.getAttribute("selected")).isNull(); + assertThat(initiallySelected.getAttribute("selected")).isEqualTo("true"); initiallyNotSelected.click(); - assertThat(neverSelected.getAttribute("selected"), equalTo(null)); - assertThat(initiallyNotSelected.getAttribute("selected"), equalTo("true")); - assertThat(initiallySelected.getAttribute("selected"), equalTo(null)); + assertThat(neverSelected.getAttribute("selected")).isNull(); + assertThat(initiallyNotSelected.getAttribute("selected")).isEqualTo("true"); + assertThat(initiallySelected.getAttribute("selected")).isNull(); } @Test @@ -192,10 +181,10 @@ public void testShouldReturnTheValueOfSelectedForOptionsOnlyIfTheyAreSelected() List options = selectBox.findElements(By.tagName("option")); WebElement one = options.get(0); WebElement two = options.get(1); - assertThat(one.isSelected(), is(true)); - assertThat(two.isSelected(), is(false)); - assertThat(one.getAttribute("selected"), equalTo("true")); - assertThat(two.getAttribute("selected"), equalTo(null)); + assertThat(one.isSelected()).isTrue(); + assertThat(two.isSelected()).isFalse(); + assertThat(one.getAttribute("selected")).isEqualTo("true"); + assertThat(two.getAttribute("selected")).isNull(); } @Test @@ -205,7 +194,7 @@ public void testShouldReturnValueOfClassAttributeOfAnElement() { WebElement heading = driver.findElement(By.xpath("//h1")); String className = heading.getAttribute("class"); - assertThat(className, equalTo("header")); + assertThat(className).isEqualTo("header"); } @Test @@ -214,7 +203,7 @@ public void testShouldReturnTheContentsOfATextAreaAsItsValue() { String value = driver.findElement(By.id("withText")).getAttribute("value"); - assertThat(value, equalTo("Example text")); + assertThat(value).isEqualTo("Example text"); } @Test @@ -223,7 +212,7 @@ public void testShouldReturnInnerHtml() { driver.get(pages.simpleTestPage); String html = driver.findElement(By.id("wrappingtext")).getAttribute("innerHTML"); - assertThat(html, containsString("")); + assertThat(html).contains(""); } @Test @@ -233,12 +222,12 @@ public void testShouldTreatReadonlyAsAValue() { WebElement element = driver.findElement(By.name("readonly")); String readonly = element.getAttribute("readonly"); - assertNotNull(readonly); + assertThat(readonly).isNotNull(); WebElement textInput = driver.findElement(By.name("x")); String notReadonly = textInput.getAttribute("readonly"); - assertFalse(readonly.equals(notReadonly)); + assertThat(readonly).isNotEqualTo(notReadonly); } @Test @@ -250,14 +239,14 @@ public void testShouldReturnHiddenTextForTextContentAttribute() { WebElement element = driver.findElement(By.id("hiddenline")); String textContent = element.getAttribute("textContent"); - assertEquals(textContent, "A hidden line of text"); + assertThat(textContent).isEqualTo("A hidden line of text"); } @Test public void testShouldGetNumericAtribute() { driver.get(pages.formPage); WebElement element = driver.findElement(By.id("withText")); - assertThat(element.getAttribute("rows"), is("5")); + assertThat(element.getAttribute("rows")).isEqualTo("5"); } @Test @@ -266,7 +255,7 @@ public void testCanReturnATextApproximationOfTheStyleAttribute() { String style = driver.findElement(By.id("red-item")).getAttribute("style"); - assertTrue(style.toLowerCase().contains("background-color")); + assertThat(style.toLowerCase().contains("background-color")).isTrue(); } @Test @@ -282,11 +271,11 @@ public void testShouldCorrectlyReportValueOfColspan() { WebElement th1 = driver.findElement(By.id("th1")); WebElement td2 = driver.findElement(By.id("td2")); - assertEquals("th1 id", "th1", th1.getAttribute("id")); - assertEquals("th1 colspan should be 3", "3", th1.getAttribute("colspan")); + assertThat(th1.getAttribute("id")).isEqualTo("th1"); + assertThat(th1.getAttribute("colspan")).isEqualTo("3"); - assertEquals("td2 id", "td2", td2.getAttribute("id")); - assertEquals("td2 colspan should be 2", "2", td2.getAttribute("colspan")); + assertThat(td2.getAttribute("id")).isEqualTo("td2"); + assertThat(td2.getAttribute("colspan")).isEqualTo("2"); } // This is a test-case re-creating issue 900. @@ -299,13 +288,13 @@ public void testShouldReturnValueOfOnClickAttribute() { String onClickValue = mouseclickDiv.getAttribute("onclick"); String expectedOnClickValue = "displayMessage('mouse click');"; - assertThat("Javascript code expected", onClickValue, anyOf( - equalTo("javascript:" + expectedOnClickValue), // Non-IE - equalTo("function anonymous()\n{\n" + expectedOnClickValue + "\n}"), // IE - equalTo("function onclick()\n{\n" + expectedOnClickValue + "\n}"))); // IE + assertThat(onClickValue).as("Javascript code").isIn( + "javascript:" + expectedOnClickValue, // Non-IE + "function anonymous()\n{\n" + expectedOnClickValue + "\n}", // IE + "function onclick()\n{\n" + expectedOnClickValue + "\n}"); // IE WebElement mousedownDiv = driver.findElement(By.id("mousedown")); - assertEquals(null, mousedownDiv.getAttribute("onclick")); + assertThat(mousedownDiv.getAttribute("onclick")).isNull(); } @Test @@ -314,14 +303,14 @@ public void testGetAttributeDoesNotReturnAnObjectForSvgProperties() { driver.get(pages.svgPage); WebElement svgElement = driver.findElement(By.id("rotate")); - assertEquals("rotate(30)", svgElement.getAttribute("transform")); + assertThat(svgElement.getAttribute("transform")).isEqualTo("rotate(30)"); } @Test public void testCanRetrieveTheCurrentValueOfATextFormField_textInput() { driver.get(pages.formPage); WebElement element = driver.findElement(By.id("working")); - assertEquals("", element.getAttribute("value")); + assertThat(element.getAttribute("value")).isEqualTo(""); element.sendKeys("hello world"); shortWait.until(ExpectedConditions.attributeToBe(element, "value", "hello world")); } @@ -330,7 +319,7 @@ public void testCanRetrieveTheCurrentValueOfATextFormField_textInput() { public void testCanRetrieveTheCurrentValueOfATextFormField_emailInput() { driver.get(pages.formPage); WebElement element = driver.findElement(By.id("email")); - assertEquals("", element.getAttribute("value")); + assertThat(element.getAttribute("value")).isEqualTo(""); element.sendKeys("hello@example.com"); shortWait.until(ExpectedConditions.attributeToBe(element, "value", "hello@example.com")); } @@ -339,7 +328,7 @@ public void testCanRetrieveTheCurrentValueOfATextFormField_emailInput() { public void testCanRetrieveTheCurrentValueOfATextFormField_textArea() { driver.get(pages.formPage); WebElement element = driver.findElement(By.id("emptyTextArea")); - assertEquals("", element.getAttribute("value")); + assertThat(element.getAttribute("value")).isEqualTo(""); element.sendKeys("hello world"); shortWait.until(ExpectedConditions.attributeToBe(element, "value", "hello world")); } @@ -348,9 +337,9 @@ public void testCanRetrieveTheCurrentValueOfATextFormField_textArea() { public void testShouldReturnNullForNonPresentBooleanAttributes() { driver.get(pages.booleanAttributes); WebElement element1 = driver.findElement(By.id("working")); - assertNull(element1.getAttribute("required")); + assertThat(element1.getAttribute("required")).isNull(); WebElement element2 = driver.findElement(By.id("wallace")); - assertNull(element2.getAttribute("nowrap")); + assertThat(element2.getAttribute("nowrap")).isNull(); } @Test @@ -358,56 +347,56 @@ public void testShouldReturnNullForNonPresentBooleanAttributes() { public void testShouldReturnTrueForPresentBooleanAttributes() { driver.get(pages.booleanAttributes); WebElement element1 = driver.findElement(By.id("emailRequired")); - assertEquals("true", element1.getAttribute("required")); + assertThat(element1.getAttribute("required")).isEqualTo("true"); WebElement element2 = driver.findElement(By.id("emptyTextAreaRequired")); - assertEquals("true", element2.getAttribute("required")); + assertThat(element2.getAttribute("required")).isEqualTo("true"); WebElement element3 = driver.findElement(By.id("inputRequired")); - assertEquals("true", element3.getAttribute("required")); + assertThat(element3.getAttribute("required")).isEqualTo("true"); WebElement element4 = driver.findElement(By.id("textAreaRequired")); - assertEquals("true", element4.getAttribute("required")); + assertThat(element4.getAttribute("required")).isEqualTo("true"); WebElement element5 = driver.findElement(By.id("unwrappable")); - assertEquals("true", element5.getAttribute("nowrap")); + assertThat(element5.getAttribute("nowrap")).isEqualTo("true"); } @Test public void testMultipleAttributeShouldBeNullWhenNotSet() { driver.get(pages.selectPage); WebElement element = driver.findElement(By.id("selectWithoutMultiple")); - assertEquals(null, element.getAttribute("multiple")); + assertThat(element.getAttribute("multiple")).isNull(); } @Test public void testMultipleAttributeShouldBeTrueWhenSet() { driver.get(pages.selectPage); WebElement element = driver.findElement(By.id("selectWithMultipleEqualsMultiple")); - assertEquals("true", element.getAttribute("multiple")); + assertThat(element.getAttribute("multiple")).isEqualTo("true"); } @Test public void testMultipleAttributeShouldBeTrueWhenSelectHasMultipleWithValueAsBlank() { driver.get(pages.selectPage); WebElement element = driver.findElement(By.id("selectWithEmptyStringMultiple")); - assertEquals("true", element.getAttribute("multiple")); + assertThat(element.getAttribute("multiple")).isEqualTo("true"); } @Test public void testMultipleAttributeShouldBeTrueWhenSelectHasMultipleWithoutAValue() { driver.get(pages.selectPage); WebElement element = driver.findElement(By.id("selectWithMultipleWithoutValue")); - assertEquals("true", element.getAttribute("multiple")); + assertThat(element.getAttribute("multiple")).isEqualTo("true"); } @Test public void testMultipleAttributeShouldBeTrueWhenSelectHasMultipleWithValueAsSomethingElse() { driver.get(pages.selectPage); WebElement element = driver.findElement(By.id("selectWithRandomMultipleValue")); - assertEquals("true", element.getAttribute("multiple")); + assertThat(element.getAttribute("multiple")).isEqualTo("true"); } @Test public void testGetAttributeOfUserDefinedProperty() { driver.get(pages.userDefinedProperty); WebElement element = driver.findElement(By.id("d")); - assertEquals("sampleValue", element.getAttribute("dynamicProperty")); + assertThat(element.getAttribute("dynamicProperty")).isEqualTo("sampleValue"); } } diff --git a/java/client/test/org/openqa/selenium/ElementEqualityTest.java b/java/client/test/org/openqa/selenium/ElementEqualityTest.java index b5ec3148ec88e..a71e0197e2a58 100644 --- a/java/client/test/org/openqa/selenium/ElementEqualityTest.java +++ b/java/client/test/org/openqa/selenium/ElementEqualityTest.java @@ -17,8 +17,7 @@ package org.openqa.selenium; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; +import static org.assertj.core.api.Assertions.assertThat; import static org.openqa.selenium.testing.Driver.SAFARI; import org.junit.Test; @@ -38,7 +37,7 @@ public void testSameElementLookedUpDifferentWaysShouldBeEqual() { WebElement body = driver.findElement(By.tagName("body")); WebElement xbody = driver.findElements(By.xpath("//body")).get(0); - assertEquals(body, xbody); + assertThat(xbody).isEqualTo(body); } @Test @@ -47,7 +46,7 @@ public void testDifferentElementsShouldNotBeEqual() { List ps = driver.findElements(By.tagName("p")); - assertFalse(ps.get(0).equals(ps.get(1))); + assertThat(ps.get(0).equals(ps.get(1))).isFalse(); } @Test @@ -56,7 +55,7 @@ public void testSameElementLookedUpDifferentWaysUsingFindElementShouldHaveSameHa WebElement body = driver.findElement(By.tagName("body")); WebElement xbody = driver.findElement(By.xpath("//body")); - assertEquals(body.hashCode(), xbody.hashCode()); + assertThat(xbody.hashCode()).isEqualTo(body.hashCode()); } @Test @@ -65,7 +64,7 @@ public void testSameElementLookedUpDifferentWaysUsingFindElementsShouldHaveSameH List body = driver.findElements(By.tagName("body")); List xbody = driver.findElements(By.xpath("//body")); - assertEquals(body.get(0).hashCode(), xbody.get(0).hashCode()); + assertThat(xbody.get(0).hashCode()).isEqualTo(body.get(0).hashCode()); } @SwitchToTopAfterTest @@ -93,7 +92,7 @@ private void checkIdEqualityIfRemote(WebElement first, WebElement second) { String firstId = getId(unwrapIfNecessary(first)); String secondId = getId(unwrapIfNecessary(second)); - assertEquals(firstId, secondId); + assertThat(secondId).isEqualTo(firstId); } private String getId(WebElement element) { diff --git a/java/client/test/org/openqa/selenium/ElementFindingTest.java b/java/client/test/org/openqa/selenium/ElementFindingTest.java index 9438e123c79eb..2f7e80ff29ea6 100644 --- a/java/client/test/org/openqa/selenium/ElementFindingTest.java +++ b/java/client/test/org/openqa/selenium/ElementFindingTest.java @@ -17,19 +17,14 @@ package org.openqa.selenium; -import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.greaterThan; -import static org.hamcrest.Matchers.instanceOf; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.startsWith; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assume.assumeFalse; import static org.openqa.selenium.testing.Driver.CHROME; import static org.openqa.selenium.testing.Driver.IE; import static org.openqa.selenium.testing.Driver.MARIONETTE; import static org.openqa.selenium.testing.Driver.SAFARI; -import static org.openqa.selenium.testing.TestUtilities.catchThrowable; +import static org.openqa.selenium.testing.TestUtilities.isIe6; import static org.openqa.selenium.testing.TestUtilities.isOldIe; import org.junit.Test; @@ -38,7 +33,6 @@ import org.openqa.selenium.testing.NeedsFreshDriver; import org.openqa.selenium.testing.NotYetImplemented; import org.openqa.selenium.testing.SwitchToTopAfterTest; -import org.openqa.selenium.testing.TestUtilities; import java.util.List; @@ -50,14 +44,14 @@ public class ElementFindingTest extends JUnit4TestBase { public void testShouldBeAbleToFindASingleElementById() { driver.get(pages.xhtmlTestPage); WebElement element = driver.findElement(By.id("linkId")); - assertThat(element.getAttribute("id"), is("linkId")); + assertThat(element.getAttribute("id")).isEqualTo("linkId"); } @Test public void testShouldBeAbleToFindASingleElementByNumericId() { driver.get(pages.nestedPage); WebElement element = driver.findElement(By.id("2")); - assertThat(element.getAttribute("id"), is("2")); + assertThat(element.getAttribute("id")).isEqualTo("2"); } @Test @@ -67,23 +61,23 @@ public void testShouldBeAbleToFindASingleElementByNumericId() { public void testShouldBeAbleToFindASingleElementByIdWithNonAlphanumericCharacters() { driver.get(pages.nestedPage); WebElement element = driver.findElement(By.id("white space")); - assertThat(element.getText(), is("space")); + assertThat(element.getText()).isEqualTo("space"); WebElement element2 = driver.findElement(By.id("css#.chars")); - assertThat(element2.getText(), is("css escapes")); + assertThat(element2.getText()).isEqualTo("css escapes"); } @Test public void testShouldBeAbleToFindMultipleElementsById() { driver.get(pages.nestedPage); List elements = driver.findElements(By.id("test_id")); - assertThat(elements.size(), is(2)); + assertThat(elements).hasSize(2); } @Test public void testShouldBeAbleToFindMultipleElementsByNumericId() { driver.get(pages.nestedPage); List elements = driver.findElements(By.id("2")); - assertThat(elements.size(), is(8)); + assertThat(elements).hasSize(8); } @Test @@ -93,9 +87,9 @@ public void testShouldBeAbleToFindMultipleElementsByNumericId() { public void testShouldBeAbleToFindMultipleElementsByIdWithNonAlphanumericCharacters() { driver.get(pages.nestedPage); List elements = driver.findElements(By.id("white space")); - assertThat(elements.size(), is(2)); + assertThat(elements).hasSize(2); List elements2 = driver.findElements(By.id("css#.chars")); - assertThat(elements2.size(), is(2)); + assertThat(elements2).hasSize(2); } // By.id negative @@ -103,22 +97,22 @@ public void testShouldBeAbleToFindMultipleElementsByIdWithNonAlphanumericCharact @Test public void testShouldNotBeAbleToLocateByIdASingleElementThatDoesNotExist() { driver.get(pages.formPage); - Throwable t = catchThrowable(() -> driver.findElement(By.id("nonExistentButton"))); - assertThat(t, instanceOf(NoSuchElementException.class)); + assertThatExceptionOfType(NoSuchElementException.class) + .isThrownBy(() -> driver.findElement(By.id("nonExistentButton"))); } @Test public void testShouldNotBeAbleToLocateByIdMultipleElementsThatDoNotExist() { driver.get(pages.formPage); List elements = driver.findElements(By.id("nonExistentButton")); - assertThat(elements.size(), is(0)); + assertThat(elements.size()).isEqualTo(0); } @Test public void testFindingASingleElementByEmptyIdShouldThrow() { driver.get(pages.formPage); - Throwable t = catchThrowable(() -> driver.findElement(By.id(""))); - assertThat(t, instanceOf(NoSuchElementException.class)); + assertThatExceptionOfType(NoSuchElementException.class) + .isThrownBy(() -> driver.findElement(By.id(""))); } @Test @@ -126,21 +120,21 @@ public void testFindingASingleElementByEmptyIdShouldThrow() { public void testFindingMultipleElementsByEmptyIdShouldReturnEmptyList() { driver.get(pages.formPage); List elements = driver.findElements(By.id("")); - assertThat(elements.size(), is(0)); + assertThat(elements.size()).isEqualTo(0); } @Test public void testFindingASingleElementByIdWithSpaceShouldThrow() { driver.get(pages.formPage); - Throwable t = catchThrowable(() -> driver.findElement(By.id("nonexistent button"))); - assertThat(t, instanceOf(NoSuchElementException.class)); + assertThatExceptionOfType(NoSuchElementException.class) + .isThrownBy(() -> driver.findElement(By.id("nonexistent button"))); } @Test public void testFindingMultipleElementsByIdWithSpaceShouldReturnEmptyList() { driver.get(pages.formPage); List elements = driver.findElements(By.id("nonexistent button")); - assertThat(elements.size(), is(0)); + assertThat(elements.size()).isEqualTo(0); } // By.name positive @@ -149,21 +143,21 @@ public void testFindingMultipleElementsByIdWithSpaceShouldReturnEmptyList() { public void testShouldBeAbleToFindASingleElementByName() { driver.get(pages.formPage); WebElement element = driver.findElement(By.name("checky")); - assertThat(element.getAttribute("value"), is("furrfu")); + assertThat(element.getAttribute("value")).isEqualTo("furrfu"); } @Test public void testShouldBeAbleToFindMultipleElementsByName() { driver.get(pages.nestedPage); List elements = driver.findElements(By.name("checky")); - assertThat(elements.size(), greaterThan(1)); + assertThat(elements.size()).isGreaterThan(1); } @Test public void testShouldBeAbleToFindAnElementThatDoesNotSupportTheNameProperty() { driver.get(pages.nestedPage); WebElement element = driver.findElement(By.name("div1")); - assertThat(element.getAttribute("name"), is("div1")); + assertThat(element.getAttribute("name")).isEqualTo("div1"); } // By.name negative @@ -171,43 +165,43 @@ public void testShouldBeAbleToFindAnElementThatDoesNotSupportTheNameProperty() { @Test public void testShouldNotBeAbleToLocateByNameASingleElementThatDoesNotExist() { driver.get(pages.formPage); - Throwable t = catchThrowable(() -> driver.findElement(By.name("nonExistentButton"))); - assertThat(t, instanceOf(NoSuchElementException.class)); + assertThatExceptionOfType(NoSuchElementException.class) + .isThrownBy(() -> driver.findElement(By.name("nonExistentButton"))); } @Test public void testShouldNotBeAbleToLocateByNameMultipleElementsThatDoNotExist() { driver.get(pages.formPage); List elements = driver.findElements(By.name("nonExistentButton")); - assertThat(elements.size(), is(0)); + assertThat(elements).hasSize(0); } @Test public void testFindingASingleElementByEmptyNameShouldThrow() { driver.get(pages.formPage); - Throwable t = catchThrowable(() -> driver.findElement(By.name(""))); - assertThat(t, instanceOf(NoSuchElementException.class)); + assertThatExceptionOfType(NoSuchElementException.class) + .isThrownBy(() -> driver.findElement(By.name(""))); } @Test public void testFindingMultipleElementsByEmptyNameShouldReturnEmptyList() { driver.get(pages.formPage); List elements = driver.findElements(By.name("")); - assertThat(elements.size(), is(0)); + assertThat(elements).hasSize(0); } @Test public void testFindingASingleElementByNameWithSpaceShouldThrow() { driver.get(pages.formPage); - Throwable t = catchThrowable(() -> driver.findElement(By.name("nonexistent button"))); - assertThat(t, instanceOf(NoSuchElementException.class)); + assertThatExceptionOfType(NoSuchElementException.class) + .isThrownBy(() -> driver.findElement(By.name("nonexistent button"))); } @Test public void testFindingMultipleElementsByNameWithSpaceShouldReturnEmptyList() { driver.get(pages.formPage); List elements = driver.findElements(By.name("nonexistent button")); - assertThat(elements.size(), is(0)); + assertThat(elements).hasSize(0); } // By.tagName positive @@ -216,14 +210,14 @@ public void testFindingMultipleElementsByNameWithSpaceShouldReturnEmptyList() { public void testShouldBeAbleToFindASingleElementByTagName() { driver.get(pages.formPage); WebElement element = driver.findElement(By.tagName("input")); - assertThat(element.getTagName().toLowerCase(), is("input")); + assertThat(element.getTagName().toLowerCase()).isEqualTo("input"); } @Test public void testShouldBeAbleToFindMultipleElementsByTagName() { driver.get(pages.formPage); List elements = driver.findElements(By.tagName("input")); - assertThat(elements.size(), greaterThan(1)); + assertThat(elements.size()).isGreaterThan(1); } // By.tagName negative @@ -231,44 +225,44 @@ public void testShouldBeAbleToFindMultipleElementsByTagName() { @Test public void testShouldNotBeAbleToLocateByTagNameASingleElementThatDoesNotExist() { driver.get(pages.formPage); - Throwable t = catchThrowable(() -> driver.findElement(By.tagName("nonExistentButton"))); - assertThat(t, instanceOf(NoSuchElementException.class)); + assertThatExceptionOfType(NoSuchElementException.class) + .isThrownBy(() -> driver.findElement(By.tagName("nonExistentButton"))); } @Test public void testShouldNotBeAbleToLocateByTagNameMultipleElementsThatDoNotExist() { driver.get(pages.formPage); List elements = driver.findElements(By.tagName("nonExistentButton")); - assertThat(elements.size(), is(0)); + assertThat(elements).hasSize(0); } @Test public void testFindingASingleElementByEmptyTagNameShouldThrow() { driver.get(pages.formPage); - Throwable t = catchThrowable(() -> driver.findElement(By.tagName(""))); - assertThat(t, instanceOf(NoSuchElementException.class)); + assertThatExceptionOfType(NoSuchElementException.class) + .isThrownBy(() -> driver.findElement(By.tagName(""))); } @Test @NotYetImplemented(SAFARI) public void testFindingMultipleElementsByEmptyTagNameShouldThrow() { driver.get(pages.formPage); - Throwable t = catchThrowable(() -> driver.findElements(By.tagName(""))); - assertThat(t, instanceOf(NoSuchElementException.class)); + assertThatExceptionOfType(NoSuchElementException.class) + .isThrownBy(() -> driver.findElements(By.tagName(""))); } @Test public void testFindingASingleElementByTagNameWithSpaceShouldThrow() { driver.get(pages.formPage); - Throwable t = catchThrowable(() -> driver.findElement(By.tagName("nonexistent button"))); - assertThat(t, instanceOf(NoSuchElementException.class)); + assertThatExceptionOfType(NoSuchElementException.class) + .isThrownBy(() -> driver.findElement(By.tagName("nonexistent button"))); } @Test public void testFindingMultipleElementsByTagNameWithSpaceShouldReturnEmptyList() { driver.get(pages.formPage); List elements = driver.findElements(By.tagName("nonexistent button")); - assertThat(elements.size(), is(0)); + assertThat(elements).hasSize(0); } // By.className positive @@ -277,50 +271,50 @@ public void testFindingMultipleElementsByTagNameWithSpaceShouldReturnEmptyList() public void testShouldBeAbleToFindASingleElementByClass() { driver.get(pages.xhtmlTestPage); WebElement element = driver.findElement(By.className("extraDiv")); - assertThat(element.getText(), startsWith("Another div starts here.")); + assertThat(element.getText()).startsWith("Another div starts here."); } @Test public void testShouldBeAbleToFindMultipleElementsByClassName() { driver.get(pages.xhtmlTestPage); List elements = driver.findElements(By.className("nameC")); - assertThat(elements.size(), greaterThan(1)); + assertThat(elements.size()).isGreaterThan(1); } @Test public void testShouldFindElementByClassWhenItIsTheFirstNameAmongMany() { driver.get(pages.xhtmlTestPage); WebElement element = driver.findElement(By.className("nameA")); - assertThat(element.getText(), is("An H2 title")); + assertThat(element.getText()).isEqualTo("An H2 title"); } @Test public void testShouldFindElementByClassWhenItIsTheLastNameAmongMany() { driver.get(pages.xhtmlTestPage); WebElement element = driver.findElement(By.className("nameC")); - assertThat(element.getText(), is("An H2 title")); + assertThat(element.getText()).isEqualTo("An H2 title"); } @Test public void testShouldFindElementByClassWhenItIsInTheMiddleAmongMany() { driver.get(pages.xhtmlTestPage); WebElement element = driver.findElement(By.className("nameBnoise")); - assertThat(element.getText(), is("An H2 title")); + assertThat(element.getText()).isEqualTo("An H2 title"); } @Test public void testShouldFindElementByClassWhenItsNameIsSurroundedByWhitespace() { driver.get(pages.xhtmlTestPage); WebElement element = driver.findElement(By.className("spaceAround")); - assertThat(element.getText(), is("Spaced out")); + assertThat(element.getText()).isEqualTo("Spaced out"); } @Test public void testShouldFindElementsByClassWhenItsNameIsSurroundedByWhitespace() { driver.get(pages.xhtmlTestPage); List elements = driver.findElements(By.className("spaceAround")); - assertThat(elements.size(), is(1)); - assertThat(elements.get(0).getText(), is("Spaced out")); + assertThat(elements).hasSize(1); + assertThat(elements.get(0).getText()).isEqualTo("Spaced out"); } // By.className negative @@ -328,30 +322,30 @@ public void testShouldFindElementsByClassWhenItsNameIsSurroundedByWhitespace() { @Test public void testShouldNotFindElementByClassWhenTheNameQueriedIsShorterThanCandidateName() { driver.get(pages.xhtmlTestPage); - Throwable t = catchThrowable(() -> driver.findElement(By.className("nameB"))); - assertThat(t, instanceOf(NoSuchElementException.class)); + assertThatExceptionOfType(NoSuchElementException.class) + .isThrownBy(() -> driver.findElement(By.className("nameB"))); } @Test public void testFindingASingleElementByEmptyClassNameShouldThrow() { driver.get(pages.xhtmlTestPage); - Throwable t = catchThrowable(() -> driver.findElement(By.className(""))); - assertThat(t, instanceOf(NoSuchElementException.class)); + assertThatExceptionOfType(NoSuchElementException.class) + .isThrownBy(() -> driver.findElement(By.className(""))); } @Test @NotYetImplemented(SAFARI) public void testFindingMultipleElementsByEmptyClassNameShouldThrow() { driver.get(pages.xhtmlTestPage); - Throwable t = catchThrowable(() -> driver.findElements(By.className(""))); - assertThat(t, instanceOf(NoSuchElementException.class)); + assertThatExceptionOfType(NoSuchElementException.class) + .isThrownBy(() -> driver.findElements(By.className(""))); } @Test public void testFindingASingleElementByCompoundClassNameShouldThrow() { driver.get(pages.xhtmlTestPage); - Throwable t = catchThrowable(() -> driver.findElement(By.className("a b"))); - assertThat(t, instanceOf(NoSuchElementException.class)); + assertThatExceptionOfType(NoSuchElementException.class) + .isThrownBy(() -> driver.findElement(By.className("a b"))); } @Test @@ -359,15 +353,15 @@ public void testFindingASingleElementByCompoundClassNameShouldThrow() { @NotYetImplemented(SAFARI) public void testFindingMultipleElementsByCompoundClassNameShouldThrow() { driver.get(pages.xhtmlTestPage); - Throwable t = catchThrowable(() -> driver.findElements(By.className("a b"))); - assertThat(t, instanceOf(NoSuchElementException.class)); + assertThatExceptionOfType(NoSuchElementException.class) + .isThrownBy(() -> driver.findElements(By.className("a b"))); } @Test public void testFindingASingleElementByInvalidClassNameShouldThrow() { driver.get(pages.xhtmlTestPage); - Throwable t = catchThrowable(() -> driver.findElement(By.className("!@#$%^&*"))); - assertThat(t, instanceOf(NoSuchElementException.class)); + assertThatExceptionOfType(NoSuchElementException.class) + .isThrownBy(() -> driver.findElement(By.className("!@#$%^&*"))); } @Test @@ -375,8 +369,8 @@ public void testFindingASingleElementByInvalidClassNameShouldThrow() { @NotYetImplemented(SAFARI) public void testFindingMultipleElementsByInvalidClassNameShouldThrow() { driver.get(pages.xhtmlTestPage); - Throwable t = catchThrowable(() -> driver.findElements(By.className("!@#$%^&*"))); - assertThat(t, instanceOf(NoSuchElementException.class)); + assertThatExceptionOfType(NoSuchElementException.class) + .isThrownBy(() -> driver.findElements(By.className("!@#$%^&*"))); } // By.xpath positive @@ -385,31 +379,31 @@ public void testFindingMultipleElementsByInvalidClassNameShouldThrow() { public void testShouldBeAbleToFindASingleElementByXPath() { driver.get(pages.xhtmlTestPage); WebElement element = driver.findElement(By.xpath("//h1")); - assertThat(element.getText(), is("XHTML Might Be The Future")); + assertThat(element.getText()).isEqualTo("XHTML Might Be The Future"); } @Test public void testShouldBeAbleToFindMultipleElementsByXPath() { driver.get(pages.xhtmlTestPage); List elements = driver.findElements(By.xpath("//div")); - assertThat(elements.size(), is(13)); + assertThat(elements).hasSize(13); } @Test public void testShouldBeAbleToFindManyElementsRepeatedlyByXPath() { driver.get(pages.xhtmlTestPage); String xpathString = "//node()[contains(@id,'id')]"; - assertThat(driver.findElements(By.xpath(xpathString)).size(), is(3)); + assertThat(driver.findElements(By.xpath(xpathString))).hasSize(3); xpathString = "//node()[contains(@id,'nope')]"; - assertThat(driver.findElements(By.xpath(xpathString)).size(), is(0)); + assertThat(driver.findElements(By.xpath(xpathString))).hasSize(0); } @Test public void testShouldBeAbleToIdentifyElementsByClass() { driver.get(pages.xhtmlTestPage); WebElement header = driver.findElement(By.xpath("//h1[@class='header']")); - assertThat(header.getText(), is("XHTML Might Be The Future")); + assertThat(header.getText()).isEqualTo("XHTML Might Be The Future"); } @Test @@ -417,22 +411,22 @@ public void testShouldBeAbleToFindAnElementByXPathWithMultipleAttributes() { driver.get(pages.formPage); WebElement element = driver.findElement( By.xpath("//form[@name='optional']/input[@type='submit' and @value='Click!']")); - assertThat(element.getTagName().toLowerCase(), is("input")); - assertThat(element.getAttribute("value"), is("Click!")); + assertThat(element.getTagName()).isEqualToIgnoringCase("input"); + assertThat(element.getAttribute("value")).isEqualTo("Click!"); } @Test public void testFindingALinkByXpathShouldLocateAnElementWithTheGivenText() { driver.get(pages.xhtmlTestPage); WebElement element = driver.findElement(By.xpath("//a[text()='click me']")); - assertThat(element.getText(), is("click me")); + assertThat(element.getText()).isEqualTo("click me"); } @Test public void testFindingALinkByXpathUsingContainsKeywordShouldWork() { driver.get(pages.nestedPage); WebElement element = driver.findElement(By.xpath("//a[contains(.,'hello world')]")); - assertThat(element.getText(), containsString("hello world")); + assertThat(element.getText()).contains("hello world"); } @Test @@ -442,7 +436,7 @@ public void testFindingALinkByXpathUsingContainsKeywordShouldWork() { public void testShouldBeAbleToFindElementByXPathWithNamespace() { driver.get(pages.svgPage); WebElement element = driver.findElement(By.xpath("//svg:svg//svg:text")); - assertThat(element.getText(), is("Test Chart")); + assertThat(element.getText()).isEqualTo("Test Chart"); } @Test @@ -452,7 +446,7 @@ public void testShouldBeAbleToFindElementByXPathWithNamespace() { public void testShouldBeAbleToFindElementByXPathInXmlDocument() { driver.get(pages.simpleXmlDocument); WebElement element = driver.findElement(By.xpath("//foo")); - assertThat(element.getText(), is("baz")); + assertThat(element.getText()).isEqualTo("baz"); } // By.xpath negative @@ -460,26 +454,26 @@ public void testShouldBeAbleToFindElementByXPathInXmlDocument() { @Test public void testShouldThrowAnExceptionWhenThereIsNoLinkToClick() { driver.get(pages.xhtmlTestPage); - Throwable t = catchThrowable(() -> driver.findElement(By.xpath("//a[@id='Not here']"))); - assertThat(t, instanceOf(NoSuchElementException.class)); + assertThatExceptionOfType(NoSuchElementException.class) + .isThrownBy(() -> driver.findElement(By.xpath("//a[@id='Not here']"))); } @Test @NotYetImplemented(SAFARI) public void testShouldThrowInvalidSelectorExceptionWhenXPathIsSyntacticallyInvalidInDriverFindElement() { driver.get(pages.formPage); - Throwable t = catchThrowable(() -> driver.findElement(By.xpath("this][isnot][valid"))); - assertThat(t, instanceOf(InvalidSelectorException.class)); + assertThatExceptionOfType(InvalidSelectorException.class) + .isThrownBy(() -> driver.findElement(By.xpath("this][isnot][valid"))); } @Test @NotYetImplemented(SAFARI) public void testShouldThrowInvalidSelectorExceptionWhenXPathIsSyntacticallyInvalidInDriverFindElements() { - assumeFalse("Ignoring xpath error test in IE6", TestUtilities.isIe6(driver)); + assumeFalse("Ignoring xpath error test in IE6", isIe6(driver)); driver.get(pages.formPage); - Throwable t = catchThrowable(() -> driver.findElements(By.xpath("this][isnot][valid"))); - assertThat(t, instanceOf(InvalidSelectorException.class)); + assertThatExceptionOfType(InvalidSelectorException.class) + .isThrownBy(() -> driver.findElements(By.xpath("this][isnot][valid"))); } @Test @@ -487,37 +481,37 @@ public void testShouldThrowInvalidSelectorExceptionWhenXPathIsSyntacticallyInval public void testShouldThrowInvalidSelectorExceptionWhenXPathIsSyntacticallyInvalidInElementFindElement() { driver.get(pages.formPage); WebElement body = driver.findElement(By.tagName("body")); - Throwable t = catchThrowable(() -> body.findElement(By.xpath("this][isnot][valid"))); - assertThat(t, instanceOf(InvalidSelectorException.class)); + assertThatExceptionOfType(InvalidSelectorException.class) + .isThrownBy(() -> body.findElement(By.xpath("this][isnot][valid"))); } @Test @NotYetImplemented(SAFARI) public void testShouldThrowInvalidSelectorExceptionWhenXPathIsSyntacticallyInvalidInElementFindElements() { - assumeFalse("Ignoring xpath error test in IE6", TestUtilities.isIe6(driver)); + assumeFalse("Ignoring xpath error test in IE6", isIe6(driver)); driver.get(pages.formPage); WebElement body = driver.findElement(By.tagName("body")); - Throwable t = catchThrowable(() -> body.findElements(By.xpath("this][isnot][valid"))); - assertThat(t, instanceOf(InvalidSelectorException.class)); + assertThatExceptionOfType(InvalidSelectorException.class) + .isThrownBy(() -> body.findElements(By.xpath("this][isnot][valid"))); } @Test @NotYetImplemented(SAFARI) public void testShouldThrowInvalidSelectorExceptionWhenXPathReturnsWrongTypeInDriverFindElement() { driver.get(pages.formPage); - Throwable t = catchThrowable(() -> driver.findElement(By.xpath("count(//input)"))); - assertThat(t, instanceOf(InvalidSelectorException.class)); + assertThatExceptionOfType(InvalidSelectorException.class) + .isThrownBy(() -> driver.findElement(By.xpath("count(//input)"))); } @Test @NotYetImplemented(SAFARI) public void testShouldThrowInvalidSelectorExceptionWhenXPathReturnsWrongTypeInDriverFindElements() { - assumeFalse("Ignoring xpath error test in IE6", TestUtilities.isIe6(driver)); + assumeFalse("Ignoring xpath error test in IE6", isIe6(driver)); driver.get(pages.formPage); - Throwable t = catchThrowable(() -> driver.findElements(By.xpath("count(//input)"))); - assertThat(t, instanceOf(InvalidSelectorException.class)); + assertThatExceptionOfType(InvalidSelectorException.class) + .isThrownBy(() -> driver.findElements(By.xpath("count(//input)"))); } @Test @@ -526,19 +520,19 @@ public void testShouldThrowInvalidSelectorExceptionWhenXPathReturnsWrongTypeInEl driver.get(pages.formPage); WebElement body = driver.findElement(By.tagName("body")); - Throwable t = catchThrowable(() -> body.findElement(By.xpath("count(//input)"))); - assertThat(t, instanceOf(InvalidSelectorException.class)); + assertThatExceptionOfType(InvalidSelectorException.class) + .isThrownBy(() -> body.findElement(By.xpath("count(//input)"))); } @Test @NotYetImplemented(SAFARI) public void testShouldThrowInvalidSelectorExceptionWhenXPathReturnsWrongTypeInElementFindElements() { - assumeFalse("Ignoring xpath error test in IE6", TestUtilities.isIe6(driver)); + assumeFalse("Ignoring xpath error test in IE6", isIe6(driver)); driver.get(pages.formPage); WebElement body = driver.findElement(By.tagName("body")); - Throwable t = catchThrowable(() -> body.findElements(By.xpath("count(//input)"))); - assertThat(t, instanceOf(InvalidSelectorException.class)); + assertThatExceptionOfType(InvalidSelectorException.class) + .isThrownBy(() -> body.findElements(By.xpath("count(//input)"))); } // By.cssSelector positive @@ -547,32 +541,32 @@ public void testShouldThrowInvalidSelectorExceptionWhenXPathReturnsWrongTypeInEl public void testShouldBeAbleToFindASingleElementByCssSelector() { driver.get(pages.xhtmlTestPage); WebElement element = driver.findElement(By.cssSelector("div.content")); - assertThat(element.getTagName().toLowerCase(), is("div")); - assertThat(element.getAttribute("class"), is("content")); + assertThat(element.getTagName()).isEqualToIgnoringCase("div"); + assertThat(element.getAttribute("class")).isEqualTo("content"); } @Test public void testShouldBeAbleToFindMultipleElementsByCssSelector() { driver.get(pages.xhtmlTestPage); List elements = driver.findElements(By.cssSelector("p")); - assertThat(elements.size(), greaterThan(1)); + assertThat(elements.size()).isGreaterThan(1); } @Test public void testShouldBeAbleToFindASingleElementByCompoundCssSelector() { driver.get(pages.xhtmlTestPage); WebElement element = driver.findElement(By.cssSelector("div.extraDiv, div.content")); - assertThat(element.getTagName().toLowerCase(), is("div")); - assertThat(element.getAttribute("class"), is("content")); + assertThat(element.getTagName()).isEqualToIgnoringCase("div"); + assertThat(element.getAttribute("class")).isEqualTo("content"); } @Test public void testShouldBeAbleToFindMultipleElementsByCompoundCssSelector() { driver.get(pages.xhtmlTestPage); List elements = driver.findElements(By.cssSelector("div.extraDiv, div.content")); - assertThat(elements.size(), greaterThan(1)); - assertThat(elements.get(0).getAttribute("class"), is("content")); - assertThat(elements.get(1).getAttribute("class"), is("extraDiv")); + assertThat(elements.size()).isGreaterThan(1); + assertThat(elements.get(0).getAttribute("class")).isEqualTo("content"); + assertThat(elements.get(1).getAttribute("class")).isEqualTo("extraDiv"); } @Test @@ -580,21 +574,21 @@ public void testShouldBeAbleToFindMultipleElementsByCompoundCssSelector() { public void testShouldBeAbleToFindAnElementByBooleanAttributeUsingCssSelector() { driver.get(appServer.whereIs("locators_tests/boolean_attribute_selected.html")); WebElement element = driver.findElement(By.cssSelector("option[selected='selected']")); - assertThat(element.getAttribute("value"), is("two")); + assertThat(element.getAttribute("value")).isEqualTo("two"); } @Test public void testShouldBeAbleToFindAnElementByBooleanAttributeUsingShortCssSelector() { driver.get(appServer.whereIs("locators_tests/boolean_attribute_selected.html")); WebElement element = driver.findElement(By.cssSelector("option[selected]")); - assertThat(element.getAttribute("value"), is("two")); + assertThat(element.getAttribute("value")).isEqualTo("two"); } @Test public void testShouldBeAbleToFindAnElementByBooleanAttributeUsingShortCssSelectorOnHtml4Page() { driver.get(appServer.whereIs("locators_tests/boolean_attribute_selected_html4.html")); WebElement element = driver.findElement(By.cssSelector("option[selected]")); - assertThat(element.getAttribute("value"), is("two")); + assertThat(element.getAttribute("value")).isEqualTo("two"); } // By.cssSelector negative @@ -602,48 +596,48 @@ public void testShouldBeAbleToFindAnElementByBooleanAttributeUsingShortCssSelect @Test public void testShouldNotFindElementByCssSelectorWhenThereIsNoSuchElement() { driver.get(pages.xhtmlTestPage); - Throwable t = catchThrowable(() -> driver.findElement(By.cssSelector(".there-is-no-such-class"))); - assertThat(t, instanceOf(NoSuchElementException.class)); + assertThatExceptionOfType(NoSuchElementException.class) + .isThrownBy(() -> driver.findElement(By.cssSelector(".there-is-no-such-class"))); } @Test public void testShouldNotFindElementsByCssSelectorWhenThereIsNoSuchElement() { driver.get(pages.xhtmlTestPage); List elements = driver.findElements(By.cssSelector(".there-is-no-such-class")); - assertThat(elements.size(), is(0)); + assertThat(elements).hasSize(0); } @Test @NotYetImplemented(SAFARI) public void testFindingASingleElementByEmptyCssSelectorShouldThrow() { driver.get(pages.xhtmlTestPage); - Throwable t = catchThrowable(() -> driver.findElement(By.cssSelector(""))); - assertThat(t, instanceOf(NoSuchElementException.class)); + assertThatExceptionOfType(NoSuchElementException.class) + .isThrownBy(() -> driver.findElement(By.cssSelector(""))); } @Test @NotYetImplemented(SAFARI) public void testFindingMultipleElementsByEmptyCssSelectorShouldThrow() { driver.get(pages.xhtmlTestPage); - Throwable t = catchThrowable(() -> driver.findElements(By.cssSelector(""))); - assertThat(t, instanceOf(NoSuchElementException.class)); + assertThatExceptionOfType(NoSuchElementException.class) + .isThrownBy(() -> driver.findElements(By.cssSelector(""))); } @Test @NotYetImplemented(SAFARI) public void testFindingASingleElementByInvalidCssSelectorShouldThrow() { driver.get(pages.xhtmlTestPage); - Throwable t = catchThrowable(() -> driver.findElement(By.cssSelector("//a/b/c[@id='1']"))); - assertThat(t, instanceOf(NoSuchElementException.class)); + assertThatExceptionOfType(NoSuchElementException.class) + .isThrownBy(() -> driver.findElement(By.cssSelector("//a/b/c[@id='1']"))); } @Test @NotYetImplemented(SAFARI) public void testFindingMultipleElementsByInvalidCssSelectorShouldThrow() { - assumeFalse("Ignoring test for lack of error in CSS in IE6", TestUtilities.isIe6(driver)); + assumeFalse("Ignoring test for lack of error in CSS in IE6", isIe6(driver)); driver.get(pages.xhtmlTestPage); - Throwable t = catchThrowable(() -> driver.findElements(By.cssSelector("//a/b/c[@id='1']"))); - assertThat(t, instanceOf(NoSuchElementException.class)); + assertThatExceptionOfType(NoSuchElementException.class) + .isThrownBy(() -> driver.findElements(By.cssSelector("//a/b/c[@id='1']"))); } // By.linkText positive @@ -652,29 +646,29 @@ public void testFindingMultipleElementsByInvalidCssSelectorShouldThrow() { public void testShouldBeAbleToFindALinkByText() { driver.get(pages.xhtmlTestPage); WebElement link = driver.findElement(By.linkText("click me")); - assertThat(link.getText(), is("click me")); + assertThat(link.getText()).isEqualTo("click me"); } @Test public void testShouldBeAbleToFindMultipleLinksByText() { driver.get(pages.xhtmlTestPage); List elements = driver.findElements(By.linkText("click me")); - assertThat(elements.size(), is(2)); + assertThat(elements).hasSize(2); } @Test public void testShouldFindElementByLinkTextContainingEqualsSign() { driver.get(pages.xhtmlTestPage); WebElement element = driver.findElement(By.linkText("Link=equalssign")); - assertThat(element.getAttribute("id"), is("linkWithEqualsSign")); + assertThat(element.getAttribute("id")).isEqualTo("linkWithEqualsSign"); } @Test public void testShouldFindMultipleElementsByLinkTextContainingEqualsSign() { driver.get(pages.xhtmlTestPage); List elements = driver.findElements(By.linkText("Link=equalssign")); - assertEquals(1, elements.size()); - assertThat(elements.get(0).getAttribute("id"), is("linkWithEqualsSign")); + assertThat(elements).hasSize(1); + assertThat(elements.get(0).getAttribute("id")).isEqualTo("linkWithEqualsSign"); } @Test @@ -685,7 +679,7 @@ public void findsByLinkTextOnXhtmlPage() { driver.get(appServer.whereIs("actualXhtmlPage.xhtml")); String linkText = "Foo"; WebElement element = driver.findElement(By.linkText(linkText)); - assertThat(element.getText(), is(linkText)); + assertThat(element.getText()).isEqualTo(linkText); } @Test @@ -694,7 +688,7 @@ public void testLinkWithFormattingTags() { WebElement elem = driver.findElement(By.id("links")); WebElement res = elem.findElement(By.partialLinkText("link with formatting tags")); - assertThat(res.getText(), is("link with formatting tags")); + assertThat(res.getText()).isEqualTo("link with formatting tags"); } @Test @@ -702,8 +696,8 @@ public void testLinkWithFormattingTags() { public void testDriverCanGetLinkByLinkTestIgnoringTrailingWhitespace() { driver.get(pages.simpleTestPage); WebElement link = driver.findElement(By.linkText("link with trailing space")); - assertThat(link.getAttribute("id"), is("linkWithTrailingSpace")); - assertThat(link.getText(), is("link with trailing space")); + assertThat(link.getAttribute("id")).isEqualTo("linkWithTrailingSpace"); + assertThat(link.getText()).isEqualTo("link with trailing space"); } // By.linkText negative @@ -711,15 +705,15 @@ public void testDriverCanGetLinkByLinkTestIgnoringTrailingWhitespace() { @Test public void testShouldNotBeAbleToLocateByLinkTextASingleElementThatDoesNotExist() { driver.get(pages.xhtmlTestPage); - Throwable t = catchThrowable(() -> driver.findElement(By.linkText("Not here either"))); - assertThat(t, instanceOf(NoSuchElementException.class)); + assertThatExceptionOfType(NoSuchElementException.class) + .isThrownBy(() -> driver.findElement(By.linkText("Not here either"))); } @Test public void testShouldNotBeAbleToLocateByLinkTextMultipleElementsThatDoNotExist() { driver.get(pages.xhtmlTestPage); List elements = driver.findElements(By.linkText("Not here either")); - assertThat(elements.size(), is(0)); + assertThat(elements.size()).isEqualTo(0); } // By.partialLinkText positive @@ -728,29 +722,29 @@ public void testShouldNotBeAbleToLocateByLinkTextMultipleElementsThatDoNotExist( public void testShouldBeAbleToFindMultipleElementsByPartialLinkText() { driver.get(pages.xhtmlTestPage); List elements = driver.findElements(By.partialLinkText("ick me")); - assertThat(elements.size(), is(2)); + assertThat(elements.size()).isEqualTo(2); } @Test public void testShouldBeAbleToFindASingleElementByPartialLinkText() { driver.get(pages.xhtmlTestPage); WebElement element = driver.findElement(By.partialLinkText("anon")); - assertThat(element.getText(), containsString("anon")); + assertThat(element.getText()).contains("anon"); } @Test public void testShouldFindElementByPartialLinkTextContainingEqualsSign() { driver.get(pages.xhtmlTestPage); WebElement element = driver.findElement(By.partialLinkText("Link=")); - assertThat(element.getAttribute("id"), is("linkWithEqualsSign")); + assertThat(element.getAttribute("id")).isEqualTo("linkWithEqualsSign"); } @Test public void testShouldFindMultipleElementsByPartialLinkTextContainingEqualsSign() { driver.get(pages.xhtmlTestPage); List elements = driver.findElements(By.partialLinkText("Link=")); - assertThat(elements.size(), is(1)); - assertThat(elements.get(0).getAttribute("id"), is("linkWithEqualsSign")); + assertThat(elements).hasSize(1); + assertThat(elements.get(0).getAttribute("id")).isEqualTo("linkWithEqualsSign"); } // Misc tests @@ -760,7 +754,7 @@ public void testDriverShouldBeAbleToFindElementsAfterLoadingMoreThanOnePageAtATi driver.get(pages.formPage); driver.get(pages.xhtmlTestPage); WebElement link = driver.findElement(By.linkText("click me")); - assertThat(link.getText(), is("click me")); + assertThat(link.getText()).isEqualTo("click me"); } // You don't want to ask why this is here @@ -769,38 +763,38 @@ public void testWhenFindingByNameShouldNotReturnById() { driver.get(pages.formPage); WebElement element = driver.findElement(By.name("id-name1")); - assertThat(element.getAttribute("value"), is("name")); + assertThat(element.getAttribute("value")).isEqualTo("name"); element = driver.findElement(By.id("id-name1")); - assertThat(element.getAttribute("value"), is("id")); + assertThat(element.getAttribute("value")).isEqualTo("id"); element = driver.findElement(By.name("id-name2")); - assertThat(element.getAttribute("value"), is("name")); + assertThat(element.getAttribute("value")).isEqualTo("name"); element = driver.findElement(By.id("id-name2")); - assertThat(element.getAttribute("value"), is("id")); + assertThat(element.getAttribute("value")).isEqualTo("id"); } @Test public void testShouldBeAbleToFindAHiddenElementsByName() { driver.get(pages.formPage); WebElement element = driver.findElement(By.name("hidden")); - assertThat(element.getAttribute("name"), is("hidden")); + assertThat(element.getAttribute("name")).isEqualTo("hidden"); } @Test public void testShouldNotBeAbleToFindAnElementOnABlankPage() { driver.get("about:blank"); - Throwable t = catchThrowable(() -> driver.findElement(By.tagName("a"))); - assertThat(t, instanceOf(NoSuchElementException.class)); + assertThatExceptionOfType(NoSuchElementException.class) + .isThrownBy(() -> driver.findElement(By.tagName("a"))); } @NeedsFreshDriver @Test public void testShouldNotBeAbleToLocateASingleElementOnABlankPage() { // Note we're on the default start page for the browser at this point. - Throwable t = catchThrowable(() -> driver.findElement(By.id("nonExistantButton"))); - assertThat(t, instanceOf(NoSuchElementException.class)); + assertThatExceptionOfType(NoSuchElementException.class) + .isThrownBy(() -> driver.findElement(By.id("nonExistantButton"))); } @SwitchToTopAfterTest @@ -810,8 +804,8 @@ public void testAnElementFoundInADifferentFrameIsStale() { driver.switchTo().frame("inner"); WebElement element = driver.findElement(By.id("oneline")); driver.switchTo().defaultContent(); - Throwable t = catchThrowable(element::getText); - assertThat(t, instanceOf(StaleElementReferenceException.class)); + assertThatExceptionOfType(StaleElementReferenceException.class) + .isThrownBy(element::getText); } @SwitchToTopAfterTest @@ -832,8 +826,8 @@ public void testAnElementFoundInADifferentFrameViaJsCanBeUsed() { WebElement second = driver.findElement(By.id("oneline")); - assertEquals(first, element); - assertEquals(second, element); + assertThat(element).isEqualTo(first); + assertThat(element).isEqualTo(second); } } diff --git a/java/client/test/org/openqa/selenium/ElementSelectingTest.java b/java/client/test/org/openqa/selenium/ElementSelectingTest.java index b5a1e74dacb49..274b6583c0a0b 100644 --- a/java/client/test/org/openqa/selenium/ElementSelectingTest.java +++ b/java/client/test/org/openqa/selenium/ElementSelectingTest.java @@ -17,10 +17,7 @@ package org.openqa.selenium; -import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; import org.openqa.selenium.support.ui.ExpectedConditions; @@ -98,11 +95,11 @@ public void testClickingOnASelectedRadioButtonShouldLeaveItSelected() { driver.get(pages.formPage); WebElement button = enabledSelectedRadioButton(); - assertTrue(button.isSelected()); + assertThat(button.isSelected()).isTrue(); button.click(); - assertTrue(button.isSelected()); + assertThat(button.isSelected()).isTrue(); } @Test @@ -174,16 +171,16 @@ private void assertSelected(WebElement element) { private void assertSelected(WebElement element, boolean isSelected) { wait.until(ExpectedConditions.elementSelectionStateToBe(element, isSelected)); - assertThat( - String.format("Expected element %s to be %s but was %s", - describe(element), selectedToString(isSelected), selectedToString(!isSelected)), - element.isSelected(), is(isSelected)); + assertThat(element.isSelected()) + .describedAs("Expected element %s to be %s", + describe(element), selectedToString(isSelected), selectedToString(!isSelected)) + .isEqualTo(isSelected); } private void assertCannotSelect(WebElement element) { boolean previous = element.isSelected(); element.click(); - assertEquals(previous, element.isSelected()); + assertThat(element.isSelected()).isEqualTo(previous); } private void assertCanSelect(WebElement element) { @@ -219,12 +216,10 @@ private void assertCanToggle(WebElement element) { private void assertTogglingSwapsSelectedStateFrom(WebElement element, boolean originalState) { element.click(); boolean isNowSelected = element.isSelected(); - assertThat( - String.format("Expected element %s to have been toggled to %s but was %s", - describe(element), - selectedToString(!originalState), - selectedToString(originalState)), - isNowSelected, is(!(originalState))); + assertThat(isNowSelected) + .describedAs("Expected element %s to have been toggled to %s", + describe(element), selectedToString(!originalState)) + .isEqualTo(!(originalState)); assertSelected(element, !originalState); } diff --git a/java/client/test/org/openqa/selenium/ErrorsTest.java b/java/client/test/org/openqa/selenium/ErrorsTest.java index c15787020043f..d5861f001be22 100644 --- a/java/client/test/org/openqa/selenium/ErrorsTest.java +++ b/java/client/test/org/openqa/selenium/ErrorsTest.java @@ -17,7 +17,7 @@ package org.openqa.selenium; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import static org.openqa.selenium.testing.Driver.IE; import org.junit.Test; @@ -39,6 +39,6 @@ public void testShouldNotGenerateErrorsWhenOpeningANewPage() { driver.get(pages.errorsPage); Object result = ((JavascriptExecutor) driver). executeScript("return window.ERRORS.join('\\n');"); - assertEquals("Should have no errors", "", result); + assertThat(result).isEqualTo(""); } } diff --git a/java/client/test/org/openqa/selenium/ExecutingAsyncJavascriptTest.java b/java/client/test/org/openqa/selenium/ExecutingAsyncJavascriptTest.java index 302b506af1658..9ab288e6a85c1 100644 --- a/java/client/test/org/openqa/selenium/ExecutingAsyncJavascriptTest.java +++ b/java/client/test/org/openqa/selenium/ExecutingAsyncJavascriptTest.java @@ -17,25 +17,16 @@ package org.openqa.selenium; -import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.instanceOf; -import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static com.google.common.base.Throwables.getRootCause; +import static java.util.concurrent.TimeUnit.MILLISECONDS; import static org.junit.Assume.assumeTrue; import static org.openqa.selenium.testing.Driver.CHROME; import static org.openqa.selenium.testing.Driver.HTMLUNIT; import static org.openqa.selenium.testing.Driver.IE; import static org.openqa.selenium.testing.Driver.MARIONETTE; import static org.openqa.selenium.testing.Driver.SAFARI; -import static org.openqa.selenium.testing.TestUtilities.catchThrowable; - -import com.google.common.base.Throwables; import org.junit.Before; import org.junit.Test; @@ -44,6 +35,7 @@ import org.openqa.selenium.testing.NeedsLocalEnvironment; import org.openqa.selenium.testing.NotYetImplemented; +import java.util.Arrays; import java.util.Iterator; import java.util.List; import java.util.concurrent.TimeUnit; @@ -63,25 +55,28 @@ public void setUp() { public void shouldNotTimeoutIfCallbackInvokedImmediately() { driver.get(pages.ajaxyPage); Object result = executor.executeAsyncScript("arguments[arguments.length - 1](123);"); - assertThat(result, instanceOf(Number.class)); - assertEquals(123, ((Number) result).intValue()); + assertThat(result).isInstanceOf(Number.class); + assertThat(((Number) result).intValue()).isEqualTo(123); } @Test public void shouldBeAbleToReturnJavascriptPrimitivesFromAsyncScripts_NeitherNullNorUndefined() { driver.get(pages.ajaxyPage); - assertEquals(123, ((Number) executor.executeAsyncScript( - "arguments[arguments.length - 1](123);")).longValue()); - assertEquals("abc", executor.executeAsyncScript("arguments[arguments.length - 1]('abc');")); - assertFalse((Boolean) executor.executeAsyncScript("arguments[arguments.length - 1](false);")); - assertTrue((Boolean) executor.executeAsyncScript("arguments[arguments.length - 1](true);")); + assertThat(((Number) executor.executeAsyncScript( + "arguments[arguments.length - 1](123);")).longValue()).isEqualTo(123); + assertThat(executor.executeAsyncScript("arguments[arguments.length - 1]('abc');")) + .isEqualTo("abc"); + assertThat((Boolean) executor.executeAsyncScript("arguments[arguments.length - 1](false);")) + .isFalse(); + assertThat((Boolean) executor.executeAsyncScript("arguments[arguments.length - 1](true);")) + .isTrue(); } @Test public void shouldBeAbleToReturnJavascriptPrimitivesFromAsyncScripts_NullAndUndefined() { driver.get(pages.ajaxyPage); - assertNull(executor.executeAsyncScript("arguments[arguments.length - 1](null)")); - assertNull(executor.executeAsyncScript("arguments[arguments.length - 1]()")); + assertThat(executor.executeAsyncScript("arguments[arguments.length - 1](null)")).isNull(); + assertThat(executor.executeAsyncScript("arguments[arguments.length - 1]()")).isNull(); } @Test @@ -89,9 +84,8 @@ public void shouldBeAbleToReturnAnArrayLiteralFromAnAsyncScript() { driver.get(pages.ajaxyPage); Object result = executor.executeAsyncScript("arguments[arguments.length - 1]([]);"); - assertNotNull("Expected not to be null!", result); - assertThat(result, instanceOf(List.class)); - assertTrue(((List) result).isEmpty()); + assertThat(result).isNotNull().isInstanceOf(List.class); + assertThat(((List) result)).isEmpty(); } @Test @@ -99,9 +93,8 @@ public void shouldBeAbleToReturnAnArrayObjectFromAnAsyncScript() { driver.get(pages.ajaxyPage); Object result = executor.executeAsyncScript("arguments[arguments.length - 1](new Array());"); - assertNotNull("Expected not to be null!", result); - assertThat(result, instanceOf(List.class)); - assertTrue(((List) result).isEmpty()); + assertThat(result).isNotNull().isInstanceOf(List.class); + assertThat(((List) result)).isEmpty(); } @Test @@ -111,16 +104,16 @@ public void shouldBeAbleToReturnArraysOfPrimitivesFromAsyncScripts() { Object result = executor.executeAsyncScript( "arguments[arguments.length - 1]([null, 123, 'abc', true, false]);"); - assertNotNull(result); - assertThat(result, instanceOf(List.class)); + assertThat(result).isNotNull(); + assertThat(result).isInstanceOf(List.class); Iterator results = ((List) result).iterator(); - assertNull(results.next()); - assertEquals(123, ((Number) results.next()).longValue()); - assertEquals("abc", results.next()); - assertTrue((Boolean) results.next()); - assertFalse((Boolean) results.next()); - assertFalse(results.hasNext()); + assertThat(results.next()).isNull(); + assertThat(((Number) results.next()).longValue()).isEqualTo(123); + assertThat(results.next()).isEqualTo("abc"); + assertThat((Boolean) results.next()).isTrue(); + assertThat((Boolean) results.next()).isFalse(); + assertThat(results.hasNext()).isFalse(); } @Test @@ -128,8 +121,8 @@ public void shouldBeAbleToReturnWebElementsFromAsyncScripts() { driver.get(pages.ajaxyPage); Object result = executor.executeAsyncScript("arguments[arguments.length - 1](document.body);"); - assertThat(result, instanceOf(WebElement.class)); - assertEquals("body", ((WebElement) result).getTagName().toLowerCase()); + assertThat(result).isInstanceOf(WebElement.class); + assertThat(((WebElement) result).getTagName()).isEqualToIgnoringCase("body"); } @Test @@ -138,31 +131,29 @@ public void shouldBeAbleToReturnArraysOfWebElementsFromAsyncScripts() { Object result = executor.executeAsyncScript( "arguments[arguments.length - 1]([document.body, document.body]);"); - assertNotNull(result); - assertThat(result, instanceOf(List.class)); + assertThat(result).isNotNull().isInstanceOf(List.class); List list = (List) result; - assertEquals(2, list.size()); - assertThat(list.get(0), instanceOf(WebElement.class)); - assertThat(list.get(1), instanceOf(WebElement.class)); - assertEquals("body", ((WebElement) list.get(0)).getTagName().toLowerCase()); - assertEquals(list.get(0), list.get(1)); + assertThat(list).hasSize(2); + assertThat(list.get(0)).isInstanceOf(WebElement.class); + assertThat(list.get(1)).isInstanceOf(WebElement.class); + assertThat(((WebElement) list.get(0)).getTagName()).isEqualToIgnoringCase("body"); + assertThat(list.get(1)).isEqualTo(list.get(0)); } @Test public void shouldTimeoutIfScriptDoesNotInvokeCallback() { driver.get(pages.ajaxyPage); // Script is expected to be async and explicitly callback, so this should timeout. - Throwable t = catchThrowable(() -> executor.executeAsyncScript("return 1 + 2;")); - assertThat(t, instanceOf(ScriptTimeoutException.class)); + assertThatExceptionOfType(ScriptTimeoutException.class) + .isThrownBy(() -> executor.executeAsyncScript("return 1 + 2;")); } @Test public void shouldTimeoutIfScriptDoesNotInvokeCallbackWithAZeroTimeout() { driver.get(pages.ajaxyPage); - Throwable t = catchThrowable( - () -> executor.executeAsyncScript("window.setTimeout(function() {}, 0);")); - assertThat(t, instanceOf(ScriptTimeoutException.class)); + assertThatExceptionOfType(ScriptTimeoutException.class) + .isThrownBy(() -> executor.executeAsyncScript("window.setTimeout(function() {}, 0);")); } @Test @@ -176,39 +167,39 @@ public void shouldNotTimeoutIfScriptCallsbackInsideAZeroTimeout() { @Test public void shouldTimeoutIfScriptDoesNotInvokeCallbackWithLongTimeout() { - driver.manage().timeouts().setScriptTimeout(500, TimeUnit.MILLISECONDS); + driver.manage().timeouts().setScriptTimeout(500, MILLISECONDS); driver.get(pages.ajaxyPage); - Throwable t = catchThrowable(() -> executor.executeAsyncScript( - "var callback = arguments[arguments.length - 1];" + - "window.setTimeout(callback, 1500);")); - assertThat(t, instanceOf(ScriptTimeoutException.class)); + assertThatExceptionOfType(ScriptTimeoutException.class) + .isThrownBy(() -> executor.executeAsyncScript( + "var callback = arguments[arguments.length - 1];" + + "window.setTimeout(callback, 1500);")); } @Test @Ignore(IE) public void shouldDetectPageLoadsWhileWaitingOnAnAsyncScriptAndReturnAnError() { driver.get(pages.ajaxyPage); - driver.manage().timeouts().setScriptTimeout(100, TimeUnit.MILLISECONDS); - Throwable t = catchThrowable( + driver.manage().timeouts().setScriptTimeout(100, MILLISECONDS); + assertThatExceptionOfType(WebDriverException.class).isThrownBy( () -> executor.executeAsyncScript("window.location = '" + pages.dynamicPage + "';")); - assertThat(t, instanceOf(WebDriverException.class)); } @Test public void shouldCatchErrorsWhenExecutingInitialScript() { driver.get(pages.ajaxyPage); - Throwable t = catchThrowable( - () -> executor.executeAsyncScript("throw Error('you should catch this!');")); - assertThat(t, instanceOf(WebDriverException.class)); + assertThatExceptionOfType(WebDriverException.class) + .isThrownBy(() -> executor.executeAsyncScript("throw Error('you should catch this!');")); } @Test public void shouldNotTimeoutWithMultipleCallsTheFirstOneBeingSynchronous() { driver.get(pages.ajaxyPage); driver.manage().timeouts().setScriptTimeout(10, TimeUnit.MILLISECONDS); - assertTrue((Boolean) executor.executeAsyncScript("arguments[arguments.length - 1](true);")); - assertTrue((Boolean) executor.executeAsyncScript( - "var cb = arguments[arguments.length - 1]; window.setTimeout(function(){cb(true);}, 9);")); + assertThat((Boolean) executor.executeAsyncScript("arguments[arguments.length - 1](true);")) + .isTrue(); + assertThat((Boolean) executor.executeAsyncScript( + "var cb = arguments[arguments.length - 1]; window.setTimeout(function(){cb(true);}, 9);")) + .isTrue(); } @Test @@ -220,23 +211,19 @@ public void shouldNotTimeoutWithMultipleCallsTheFirstOneBeingSynchronous() { public void shouldCatchErrorsWithMessageAndStacktraceWhenExecutingInitialScript() { driver.get(pages.ajaxyPage); String js = "function functionB() { throw Error('errormessage'); };" - + "function functionA() { functionB(); };" - + "functionA();"; - Throwable t = catchThrowable(() -> executor.executeAsyncScript(js)); - assertThat(t, instanceOf(WebDriverException.class)); - assertThat(t.getMessage(), containsString("errormessage")); - - Throwable rootCause = Throwables.getRootCause(t); - assertThat(rootCause.getMessage(), containsString("errormessage")); - - StackTraceElement [] st = rootCause.getStackTrace(); - boolean seen = false; - for (StackTraceElement s: st) { - if (s.getMethodName().equals("functionB")) { - seen = true; - } - } - assertTrue("Stacktrace has not js method info", seen); + + "function functionA() { functionB(); };" + + "functionA();"; + assertThatExceptionOfType(WebDriverException.class) + .isThrownBy(() -> executor.executeAsyncScript(js)) + .withMessageContaining("errormessage") + .satisfies(t -> { + Throwable rootCause = getRootCause(t); + assertThat(rootCause).hasMessageContaining("errormessage"); + assertThat(Arrays.asList(rootCause.getStackTrace())) + .extracting(StackTraceElement::getMethodName) + .contains("functionB"); + }); + } @Test @@ -245,23 +232,25 @@ public void shouldBeAbleToExecuteAsynchronousScripts() { WebElement typer = driver.findElement(By.name("typer")); typer.sendKeys("bob"); - assertEquals("bob", typer.getAttribute("value")); + assertThat(typer.getAttribute("value")).isEqualTo("bob"); driver.findElement(By.id("red")).click(); driver.findElement(By.name("submit")).click(); - assertEquals("There should only be 1 DIV at this point, which is used for the butter message", - 1, getNumDivElements()); + assertThat(getNumDivElements()) + .describedAs("There should only be 1 DIV at this point, which is used for the butter message") + .isEqualTo(1); driver.manage().timeouts().setScriptTimeout(15, TimeUnit.SECONDS); String text = (String) executor.executeAsyncScript( "var callback = arguments[arguments.length - 1];" + "window.registerListener(arguments[arguments.length - 1]);"); - assertEquals("bob", text); - assertEquals("", typer.getAttribute("value")); + assertThat(text).isEqualTo("bob"); + assertThat(typer.getAttribute("value")).isEqualTo(""); - assertEquals("There should be 1 DIV (for the butter message) + 1 DIV (for the new label)", - 2, getNumDivElements()); + assertThat(getNumDivElements()) + .describedAs("There should be 1 DIV (for the butter message) + 1 DIV (for the new label)") + .isEqualTo(2); } @Test @@ -269,7 +258,7 @@ public void shouldBeAbleToPassMultipleArgumentsToAsyncScripts() { driver.get(pages.ajaxyPage); Number result = (Number) executor.executeAsyncScript( "arguments[arguments.length - 1](arguments[0] + arguments[1]);", 1, 2); - assertEquals(3, result.intValue()); + assertThat(result.intValue()).isEqualTo(3); } @Test @@ -301,8 +290,8 @@ public void shouldBeAbleToMakeXMLHttpRequestsAndWaitForTheResponse() { driver.get(pages.ajaxyPage); driver.manage().timeouts().setScriptTimeout(3, TimeUnit.SECONDS); String response = (String) executor.executeAsyncScript(script, pages.sleepingPage + "?time=2"); - assertThat(response.trim(), - equalTo("DoneSlept for 2s")); + assertThat(response.trim()) + .isEqualTo("DoneSlept for 2s"); } @Test @@ -313,10 +302,10 @@ public void shouldBeAbleToMakeXMLHttpRequestsAndWaitForTheResponse() { @NeedsLocalEnvironment(reason = "Relies on timing") public void throwsIfScriptTriggersAlert() { driver.get(pages.simpleTestPage); - driver.manage().timeouts().setScriptTimeout(5000, TimeUnit.MILLISECONDS); - Throwable t = catchThrowable(() -> executor.executeAsyncScript( - "setTimeout(arguments[0], 200) ; setTimeout(function() { window.alert('Look! An alert!'); }, 50);")); - assertThat(t, instanceOf(UnhandledAlertException.class)); + driver.manage().timeouts().setScriptTimeout(5000, MILLISECONDS); + assertThatExceptionOfType(UnhandledAlertException.class) + .isThrownBy(() -> executor.executeAsyncScript( + "setTimeout(arguments[0], 200) ; setTimeout(function() { window.alert('Look! An alert!'); }, 50);")); // Shouldn't throw driver.getTitle(); } @@ -329,9 +318,9 @@ public void throwsIfScriptTriggersAlert() { @NeedsLocalEnvironment(reason = "Relies on timing") public void throwsIfAlertHappensDuringScript() { driver.get(pages.slowLoadingAlertPage); - driver.manage().timeouts().setScriptTimeout(5000, TimeUnit.MILLISECONDS); - Throwable t = catchThrowable(() -> executor.executeAsyncScript("setTimeout(arguments[0], 1000);")); - assertThat(t, instanceOf(UnhandledAlertException.class)); + driver.manage().timeouts().setScriptTimeout(5000, MILLISECONDS); + assertThatExceptionOfType(UnhandledAlertException.class) + .isThrownBy(() -> executor.executeAsyncScript("setTimeout(arguments[0], 1000);")); // Shouldn't throw driver.getTitle(); } @@ -344,10 +333,10 @@ public void throwsIfAlertHappensDuringScript() { @NeedsLocalEnvironment(reason = "Relies on timing") public void throwsIfScriptTriggersAlertWhichTimesOut() { driver.get(pages.simpleTestPage); - driver.manage().timeouts().setScriptTimeout(5000, TimeUnit.MILLISECONDS); - Throwable t = catchThrowable(() -> executor.executeAsyncScript( - "setTimeout(function() { window.alert('Look! An alert!'); }, 50);")); - assertThat(t, instanceOf(UnhandledAlertException.class)); + driver.manage().timeouts().setScriptTimeout(5000, MILLISECONDS); + assertThatExceptionOfType(UnhandledAlertException.class) + .isThrownBy(() -> executor.executeAsyncScript( + "setTimeout(function() { window.alert('Look! An alert!'); }, 50);")); // Shouldn't throw driver.getTitle(); } @@ -360,9 +349,9 @@ public void throwsIfScriptTriggersAlertWhichTimesOut() { @NeedsLocalEnvironment(reason = "Relies on timing") public void throwsIfAlertHappensDuringScriptWhichTimesOut() { driver.get(pages.slowLoadingAlertPage); - driver.manage().timeouts().setScriptTimeout(5000, TimeUnit.MILLISECONDS); - Throwable t = catchThrowable(() -> executor.executeAsyncScript("")); - assertThat(t, instanceOf(UnhandledAlertException.class)); + driver.manage().timeouts().setScriptTimeout(5000, MILLISECONDS); + assertThatExceptionOfType(UnhandledAlertException.class) + .isThrownBy(() -> executor.executeAsyncScript("")); // Shouldn't throw driver.getTitle(); } @@ -374,13 +363,13 @@ public void throwsIfAlertHappensDuringScriptWhichTimesOut() { @Ignore(value = SAFARI, reason = "Does not support alerts yet") @NeedsLocalEnvironment(reason = "Relies on timing") public void includesAlertTextInUnhandledAlertException() { - driver.manage().timeouts().setScriptTimeout(5000, TimeUnit.MILLISECONDS); + driver.manage().timeouts().setScriptTimeout(5000, MILLISECONDS); String alertText = "Look! An alert!"; - Throwable t = catchThrowable(() -> executor.executeAsyncScript( - "setTimeout(arguments[0], 200) ; setTimeout(function() { window.alert('" + alertText - + "'); }, 50);")); - assertThat(t, instanceOf(UnhandledAlertException.class)); - assertThat(((UnhandledAlertException) t).getAlertText(), is(alertText)); + assertThatExceptionOfType(UnhandledAlertException.class) + .isThrownBy(() -> executor.executeAsyncScript( + "setTimeout(arguments[0], 200) ; setTimeout(function() { window.alert('" + alertText + + "'); }, 50);")) + .satisfies(t -> assertThat(t.getAlertText()).isEqualTo(alertText)); } private long getNumDivElements() { diff --git a/java/client/test/org/openqa/selenium/ExecutingJavascriptTest.java b/java/client/test/org/openqa/selenium/ExecutingJavascriptTest.java index 572e58c62c2c0..be53482966a3c 100644 --- a/java/client/test/org/openqa/selenium/ExecutingJavascriptTest.java +++ b/java/client/test/org/openqa/selenium/ExecutingJavascriptTest.java @@ -17,28 +17,19 @@ package org.openqa.selenium; +import static com.google.common.base.Throwables.getRootCause; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static java.nio.charset.StandardCharsets.US_ASCII; -import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.greaterThanOrEqualTo; -import static org.hamcrest.Matchers.instanceOf; -import static org.hamcrest.Matchers.not; -import static org.hamcrest.Matchers.startsWith; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.junit.Assume.assumeTrue; +import static org.openqa.selenium.By.id; import static org.openqa.selenium.testing.Driver.CHROME; import static org.openqa.selenium.testing.Driver.HTMLUNIT; import static org.openqa.selenium.testing.Driver.IE; import static org.openqa.selenium.testing.Driver.MARIONETTE; import static org.openqa.selenium.testing.Driver.SAFARI; -import static org.openqa.selenium.testing.TestUtilities.catchThrowable; -import com.google.common.base.Throwables; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; @@ -80,8 +71,7 @@ public void testShouldBeAbleToExecuteSimpleJavascriptAndReturnAString() { Object result = executeScript("return document.title;"); - assertTrue(result instanceof String); - assertEquals("XHTML Test Page", result); + assertThat(result).isInstanceOf(String.class).isEqualTo("XHTML Test Page"); } @Test @@ -90,8 +80,8 @@ public void testShouldBeAbleToExecuteSimpleJavascriptAndReturnALong() { Object result = executeScript("return document.getElementsByName('checky').length;"); - assertTrue(result.getClass().getName(), result instanceof Long); - assertTrue((Long) result > 1); + assertThat(result).isInstanceOf(Long.class); + assertThat((Long) result).isGreaterThan(1); } @Test @@ -100,9 +90,8 @@ public void testShouldBeAbleToExecuteSimpleJavascriptAndReturnAWebElement() { Object result = executeScript("return document.getElementById('id1');"); - assertNotNull(result); - assertThat(result, instanceOf(WebElement.class)); - assertEquals("a", ((WebElement) result).getTagName().toLowerCase()); + assertThat(result).isInstanceOf(WebElement.class); + assertThat(((WebElement) result).getTagName()).isEqualToIgnoringCase("a"); } @Test @@ -111,9 +100,8 @@ public void testShouldBeAbleToExecuteSimpleJavascriptAndReturnABoolean() { Object result = executeScript("return true;"); - assertNotNull(result); - assertTrue(result instanceof Boolean); - assertTrue((Boolean) result); + assertThat(result).isInstanceOf(Boolean.class); + assertThat((Boolean) result).isTrue(); } @SuppressWarnings("unchecked") @@ -127,7 +115,8 @@ public void testShouldBeAbleToExecuteSimpleJavascriptAndReturnAStringsArray() { Object result = ((JavascriptExecutor) driver).executeScript( "return ['zero', 'one', 'two'];"); - ExecutingJavascriptTest.compareLists(expectedResult, (List) result); + assertThat(result).isInstanceOf(List.class); + compareLists(expectedResult, (List) result); } @SuppressWarnings("unchecked") @@ -141,10 +130,8 @@ public void testShouldBeAbleToExecuteSimpleJavascriptAndReturnAnArray() { subList.add(false); expectedResult.add(subList); Object result = executeScript("return ['zero', [true, false]];"); - assertNotNull(result); - assertTrue("result was: " + result + " (" + result.getClass() + ")", result instanceof List); - List list = (List) result; - assertTrue(compareLists(expectedResult, list)); + assertThat(result).isInstanceOf(List.class); + assertThat((List) result).isEqualTo(expectedResult); } @@ -154,7 +141,7 @@ public void testShouldBeAbleToExecuteJavascriptAndReturnABasicObjectLiteral() { driver.get(pages.javascriptPage); Object result = executeScript("return {abc: '123', tired: false};"); - assertTrue("result was: " + result + " (" + result.getClass() + ")", result instanceof Map); + assertThat(result).isInstanceOf(Map.class); Map map = (Map) result; Map expected = ImmutableMap.of( @@ -163,11 +150,9 @@ public void testShouldBeAbleToExecuteJavascriptAndReturnABasicObjectLiteral() { // Cannot do an exact match; Firefox 4 inserts a few extra keys in our object; this is OK, as // long as the expected keys are there. - assertThat("Expected:<" + expected + ">, but was:<" + map + ">", - map.size(), greaterThanOrEqualTo(expected.size())); + assertThat(map.size()).isGreaterThanOrEqualTo(expected.size()); for (Map.Entry entry : expected.entrySet()) { - assertEquals("Difference at key:<" + entry.getKey() + ">", - entry.getValue(), map.get(entry.getKey())); + assertThat(map.get(entry.getKey())).as("Value by key %s, )", entry.getKey()).isEqualTo(entry.getValue()); } } @@ -187,20 +172,17 @@ public void testShouldBeAbleToExecuteSimpleJavascriptAndReturnAnObjectLiteral() Object result = executeScript( "return {foo:'bar', baz: ['a', 'b', 'c'], " + "person: {first: 'John',last: 'Doe'}};"); - assertTrue("result was: " + result + " (" + result.getClass() + ")", result instanceof Map); + assertThat(result).isInstanceOf(Map.class); Map map = (Map) result; - assertThat("Expected:<" + expectedResult + ">, but was:<" + map + ">", - map.size(), greaterThanOrEqualTo(3)); - assertEquals("bar", map.get("foo")); - assertTrue(compareLists((List) expectedResult.get("baz"), - (List) map.get("baz"))); + assertThat(map.size()).isGreaterThanOrEqualTo(3); + assertThat(map.get("foo")).isEqualTo("bar"); + assertThat((List) map.get("baz")).isEqualTo((List) expectedResult.get("baz")); Map person = (Map) map.get("person"); - assertThat("Expected:<{first:John, last:Doe}>, but was:<" + person + ">", - person.size(), greaterThanOrEqualTo(2)); - assertEquals("John", person.get("first")); - assertEquals("Doe", person.get("last")); + assertThat(person.size()).isGreaterThanOrEqualTo(2); + assertThat(person.get("first")).isEqualTo("John"); + assertThat(person.get("last")).isEqualTo("Doe"); } @SuppressWarnings("unchecked") @@ -211,10 +193,10 @@ public void testShouldBeAbleToExecuteSimpleJavascriptAndReturnAComplexObject() { Object result = executeScript("return window.location;"); - assertTrue("result was: " + result + " (" + result.getClass() + ")", result instanceof Map); + assertThat(result).isInstanceOf(Map.class); Map map = (Map) result; - assertEquals("http:", map.get("protocol")); - assertEquals(pages.javascriptPage, map.get("href")); + assertThat(map.get("protocol")).isEqualTo("http:"); + assertThat(map.get("href")).isEqualTo(pages.javascriptPage); } private static boolean compareLists(List first, List second) { @@ -240,9 +222,7 @@ public void testPassingAndReturningALongShouldReturnAWholeNumber() { driver.get(pages.javascriptPage); Long expectedResult = 1L; Object result = executeScript("return arguments[0];", expectedResult); - assertTrue("Expected result to be an Integer or Long but was a " + - result.getClass(), result instanceof Integer || result instanceof Long); - assertEquals(expectedResult, result); + assertThat(result).isInstanceOfAny(Integer.class, Long.class).isEqualTo(expectedResult); } @Test @@ -250,18 +230,16 @@ public void testPassingAndReturningADoubleShouldReturnADecimal() { driver.get(pages.javascriptPage); Double expectedResult = 1.2; Object result = executeScript("return arguments[0];", expectedResult); - assertTrue("Expected result to be a Double or Float but was a " + - result.getClass(), result instanceof Float || result instanceof Double); - assertEquals(expectedResult, result); + assertThat(result).isInstanceOfAny(Float.class, Double.class).isEqualTo(expectedResult); } @Test public void testShouldThrowAnExceptionWhenTheJavascriptIsBad() { driver.get(pages.xhtmlTestPage); - Throwable t = catchThrowable(() -> executeScript("return squiggle();")); - assertThat(t, instanceOf(WebDriverException.class)); - assertThat(t.getMessage(), not(startsWith("null "))); + assertThatExceptionOfType(WebDriverException.class) + .isThrownBy(() -> executeScript("return squiggle();")) + .satisfies(t -> assertThat(t.getMessage()).doesNotStartWith("null ")); } @Test @@ -276,21 +254,16 @@ public void testShouldThrowAnExceptionWithMessageAndStacktraceWhenTheJavascriptI String js = "function functionB() { throw Error('errormessage'); };" + "function functionA() { functionB(); };" + "functionA();"; - Throwable t = catchThrowable(() -> executeScript(js)); - assertThat(t, instanceOf(WebDriverException.class)); - assertThat(t.getMessage(), containsString("errormessage")); - - Throwable rootCause = Throwables.getRootCause(t); - assertThat(rootCause.getMessage(), containsString("errormessage")); - - StackTraceElement [] st = rootCause.getStackTrace(); - boolean seen = false; - for (StackTraceElement s: st) { - if (s.getMethodName().equals("functionB")) { - seen = true; - } - } - assertTrue("Stacktrace has not js method info", seen); + assertThatExceptionOfType(WebDriverException.class) + .isThrownBy(() -> executeScript(js)) + .withMessageContaining("errormessage") + .satisfies(t -> { + Throwable rootCause = getRootCause(t); + assertThat(rootCause).hasMessageContaining("errormessage"); + assertThat(Arrays.asList(rootCause.getStackTrace())) + .extracting(StackTraceElement::getMethodName) + .contains("functionB"); + }); } @Test @@ -299,7 +272,7 @@ public void testShouldBeAbleToCallFunctionsDefinedOnThePage() { executeScript("displayMessage('I like cheese');"); String text = driver.findElement(By.id("result")).getText(); - assertEquals("I like cheese", text.trim()); + assertThat(text.trim()).isEqualTo("I like cheese"); } @Test @@ -308,23 +281,21 @@ public void testShouldBeAbleToPassAStringAnAsArgument() { String value = (String) executeScript("return arguments[0] == 'fish' ? 'fish' : 'not fish';", "fish"); - assertEquals("fish", value); + assertThat(value).isEqualTo("fish"); } @Test public void testShouldBeAbleToPassABooleanAsArgument() { driver.get(pages.javascriptPage); boolean value = (Boolean) executeScript("return arguments[0] == true;", true); - - assertTrue(value); + assertThat(value).isTrue(); } @Test public void testShouldBeAbleToPassANumberAnAsArgument() { driver.get(pages.javascriptPage); boolean value = (Boolean) executeScript("return arguments[0] == 1 ? true : false;", 1); - - assertTrue(value); + assertThat(value).isTrue(); } @Test @@ -336,7 +307,7 @@ public void testShouldBeAbleToPassAWebElementAsArgument() { "arguments[0]['flibble'] = arguments[0].getAttribute('id'); return arguments[0]['flibble'];", button); - assertEquals("plainButton", value); + assertThat(value).isEqualTo("plainButton"); } @Test @@ -344,7 +315,7 @@ public void testPassingArrayAsOnlyArgumentFlattensArray() { driver.get(pages.javascriptPage); Object[] array = new Object[]{"zero", 1, true, 3.14159, false}; String value = (String) executeScript("return arguments[0]", array); - assertEquals(array[0], value); + assertThat(value).isEqualTo(array[0]); } @Test @@ -352,7 +323,7 @@ public void testShouldBeAbleToPassAnArrayAsAdditionalArgument() { driver.get(pages.javascriptPage); Object[] array = new Object[]{"zero", 1, true, 3.14159, false}; long length = (Long) executeScript("return arguments[1].length", "string", array); - assertEquals(array.length, length); + assertThat(length).isEqualTo(array.length); } @Test @@ -363,7 +334,7 @@ public void testShouldBeAbleToPassACollectionAsArgument() { collection.add("Brie"); collection.add(7); long length = (Long) executeScript("return arguments[0].length", collection); - assertEquals(collection.size(), length); + assertThat(length).isEqualTo(collection.size()); collection = new HashSet<>(); collection.add("Gouda"); @@ -371,22 +342,21 @@ public void testShouldBeAbleToPassACollectionAsArgument() { collection.add("Stilton"); collection.add(true); length = (Long) executeScript("return arguments[0].length", collection); - assertEquals(collection.size(), length); + assertThat(length).isEqualTo(collection.size()); } @Test public void testShouldThrowAnExceptionIfAnArgumentIsNotValid() { driver.get(pages.javascriptPage); - Throwable t = catchThrowable(() -> executeScript("return arguments[0];", driver)); - assertThat(t, instanceOf(IllegalArgumentException.class)); + assertThatExceptionOfType(IllegalArgumentException.class) + .isThrownBy(() -> executeScript("return arguments[0];", driver)); } @Test public void testShouldBeAbleToPassInMoreThanOneArgument() { driver.get(pages.javascriptPage); String result = (String) executeScript("return arguments[0] + arguments[1];", "one", "two"); - - assertEquals("onetwo", result); + assertThat(result).isEqualTo("onetwo"); } @Test @@ -398,7 +368,7 @@ public void testShouldBeAbleToGrabTheBodyOfFrameOnceSwitchedTo() { String text = body.getText(); driver.switchTo().defaultContent(); - assertEquals("", text); + assertThat(text).isEqualTo(""); } @SuppressWarnings("unchecked") @@ -409,7 +379,7 @@ public void testShouldBeAbleToReturnAnArrayOfWebElements() { List items = (List) executeScript( "return document.getElementsByName('snack');"); - assertFalse(items.isEmpty()); + assertThat(items).isNotEmpty(); } @Test @@ -417,13 +387,13 @@ public void testJavascriptStringHandlingShouldWorkAsExpected() { driver.get(pages.javascriptPage); String value = (String) executeScript("return '';"); - assertEquals("", value); + assertThat(value).isEqualTo(""); value = (String) executeScript("return undefined;"); - assertNull(value); + assertThat(value).isNull(); value = (String) executeScript("return ' '"); - assertEquals(" ", value); + assertThat(value).isEqualTo(" "); } @Test @@ -432,7 +402,9 @@ public void testShouldBeAbleToExecuteABigChunkOfJavascriptCode() throws IOExcept Path jqueryFile = InProject.locate("common/src/web/jquery-1.3.2.js"); String jquery = new String(Files.readAllBytes(jqueryFile), US_ASCII); - assertTrue("The javascript code should be at least 50 KB.", jquery.length() > 50000); + assertThat(jquery.length()) + .describedAs("The javascript code should be at least 50 KB.") + .isGreaterThan(50000); // This should not throw an exception ... executeScript(jquery); } @@ -445,7 +417,7 @@ public void testShouldBeAbleToExecuteScriptAndReturnElementsList() { List resultsList = (List) executeScript(scriptToExec); - assertFalse(resultsList.isEmpty()); + assertThat(resultsList).isNotEmpty(); } @NeedsFreshDriver @@ -455,7 +427,7 @@ public void testShouldBeAbleToExecuteScriptAndReturnElementsList() { reason = "HtmlUnit: can't execute JavaScript before a page is loaded") public void testShouldBeAbleToExecuteScriptOnNoPage() { String text = (String) executeScript("return 'test';"); - assertEquals(text, "test"); + assertThat(text).isEqualTo("test"); } @Test @@ -466,7 +438,7 @@ public void testShouldBeAbleToCreateAPersistentValue() { executeScript("document.alerts.push('hello world');"); String text = (String) executeScript("return document.alerts.shift()"); - assertEquals("hello world", text); + assertThat(text).isEqualTo("hello world"); } @Test @@ -479,7 +451,7 @@ public void testCanHandleAnArrayOfElementsAsAnObjectArray() { String name = (String) ((JavascriptExecutor) driver).executeScript( "return arguments[0][0].tagName", args); - assertEquals("form", name.toLowerCase()); + assertThat(name).isEqualToIgnoringCase("form"); } @Test @@ -491,22 +463,22 @@ public void testCanPassAMapAsAParameter() { Object res = ((JavascriptExecutor) driver).executeScript("return arguments[0]['foo'][1]", args); - assertEquals(2, ((Number) res).intValue()); + assertThat(((Number) res).intValue()).isEqualTo(2); } @Test public void testShouldThrowAnExceptionWhenArgumentsWithStaleElementPassed() { driver.get(pages.simpleTestPage); - final WebElement el = driver.findElement(By.id("oneline")); + final WebElement el = driver.findElement(id("oneline")); driver.get(pages.simpleTestPage); Map args = ImmutableMap.of( "key", Arrays.asList("a", new Object[]{"zero", 1, true, 3.14159, false, el}, "c")); - Throwable t = catchThrowable(() -> executeScript("return undefined;", args)); - assertThat(t, instanceOf(StaleElementReferenceException.class)); + assertThatExceptionOfType(StaleElementReferenceException.class) + .isThrownBy(() -> executeScript("return undefined;", args)); } @Test @@ -535,8 +507,8 @@ public void shouldReturnDocumentElementIfDocumentIsReturned() { Object value = executeScript("return document"); - assertTrue(value instanceof WebElement); - assertTrue(((WebElement) value).getText().contains("A single line of text")); + assertThat(value).isInstanceOf(WebElement.class); + assertThat(((WebElement) value).getText()).contains("A single line of text"); } @Test(timeout = 10000) @@ -547,7 +519,7 @@ public void shouldHandleObjectThatThatHaveToJSONMethod() { Object value = executeScript("return window.performance.timing"); - assertTrue(value instanceof Map); + assertThat(value).isInstanceOf(Map.class); } @Test(timeout = 10000) @@ -557,8 +529,7 @@ public void shouldHandleObjectThatThatHaveToJSONMethod() { public void shouldHandleRecursiveStructures() { driver.get(pages.simpleTestPage); - Throwable t = catchThrowable(() -> executeScript( + assertThatExceptionOfType(JavascriptException.class).isThrownBy(() -> executeScript( "var obj1 = {}; var obj2 = {}; obj1['obj2'] = obj2; obj2['obj1'] = obj1; return obj1")); - assertThat(t, instanceOf(JavascriptException.class)); } } diff --git a/java/client/test/org/openqa/selenium/FormHandlingTest.java b/java/client/test/org/openqa/selenium/FormHandlingTest.java index dd36d0db2f905..1086ebc3d9a15 100644 --- a/java/client/test/org/openqa/selenium/FormHandlingTest.java +++ b/java/client/test/org/openqa/selenium/FormHandlingTest.java @@ -17,20 +17,14 @@ package org.openqa.selenium; -import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.instanceOf; -import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assume.assumeFalse; import static org.openqa.selenium.support.ui.ExpectedConditions.alertIsPresent; import static org.openqa.selenium.support.ui.ExpectedConditions.titleIs; import static org.openqa.selenium.testing.Driver.IE; import static org.openqa.selenium.testing.Driver.MARIONETTE; import static org.openqa.selenium.testing.Driver.SAFARI; -import static org.openqa.selenium.testing.TestUtilities.catchThrowable; import static org.openqa.selenium.testing.TestUtilities.isIe6; import static org.openqa.selenium.testing.TestUtilities.isIe7; @@ -51,7 +45,7 @@ public void testShouldClickOnSubmitInputElements() { driver.get(pages.formPage); driver.findElement(By.id("submitButton")).click(); wait.until(titleIs("We Arrive Here")); - assertThat(driver.getTitle(), equalTo("We Arrive Here")); + assertThat(driver.getTitle()).isEqualTo("We Arrive Here"); } @Test @@ -65,7 +59,7 @@ public void testShouldBeAbleToClickImageButtons() { driver.get(pages.formPage); driver.findElement(By.id("imageButton")).click(); wait.until(titleIs("We Arrive Here")); - assertThat(driver.getTitle(), equalTo("We Arrive Here")); + assertThat(driver.getTitle()).isEqualTo("We Arrive Here"); } @Test @@ -96,8 +90,7 @@ public void testShouldSubmitAFormWhenAnyElementWithinThatFormIsSubmitted() { public void testShouldNotBeAbleToSubmitAFormThatDoesNotExist() { driver.get(pages.formPage); WebElement element = driver.findElement(By.name("SearchableText")); - Throwable t = catchThrowable(element::submit); - assertThat(t, instanceOf(NoSuchElementException.class)); + assertThatExceptionOfType(NoSuchElementException.class).isThrownBy(element::submit); } @Test @@ -106,7 +99,7 @@ public void testShouldBeAbleToEnterTextIntoATextAreaBySettingItsValue() { WebElement textarea = driver.findElement(By.id("keyUpArea")); String cheesy = "brie and cheddar"; textarea.sendKeys(cheesy); - assertThat(textarea.getAttribute("value"), equalTo(cheesy)); + assertThat(textarea.getAttribute("value")).isEqualTo(cheesy); } @Test @@ -116,7 +109,7 @@ public void testSendKeysKeepsCapitalization() { .id("keyUpArea")); String cheesey = "BrIe And CheDdar"; textarea.sendKeys(cheesey); - assertThat(textarea.getAttribute("value"), equalTo(cheesey)); + assertThat(textarea.getAttribute("value")).isEqualTo(cheesey); } @Test @@ -127,7 +120,7 @@ public void testShouldSubmitAFormUsingTheNewlineLiteral() { WebElement input = nestedForm.findElement(By.name("x")); input.sendKeys("\n"); wait.until(titleIs("We Arrive Here")); - assertTrue(driver.getCurrentUrl().endsWith("?x=name")); + assertThat(driver.getCurrentUrl()).endsWith("?x=name"); } @Test @@ -137,7 +130,7 @@ public void testShouldSubmitAFormUsingTheEnterKey() { WebElement input = nestedForm.findElement(By.name("x")); input.sendKeys(Keys.ENTER); wait.until(titleIs("We Arrive Here")); - assertTrue(driver.getCurrentUrl().endsWith("?x=name")); + assertThat(driver.getCurrentUrl()).endsWith("?x=name"); } @Test @@ -145,21 +138,21 @@ public void testShouldEnterDataIntoFormFields() { driver.get(pages.xhtmlTestPage); WebElement element = driver.findElement(By.xpath("//form[@name='someForm']/input[@id='username']")); String originalValue = element.getAttribute("value"); - assertThat(originalValue, equalTo("change")); + assertThat(originalValue).isEqualTo("change"); element.clear(); element.sendKeys("some text"); element = driver.findElement(By.xpath("//form[@name='someForm']/input[@id='username']")); String newFormValue = element.getAttribute("value"); - assertThat(newFormValue, equalTo("some text")); + assertThat(newFormValue).isEqualTo("some text"); } @Test public void testShouldBeAbleToAlterTheContentsOfAFileUploadInputElement() throws IOException { driver.get(pages.formPage); WebElement uploadElement = driver.findElement(By.id("upload")); - assertThat(uploadElement.getAttribute("value"), equalTo("")); + assertThat(uploadElement.getAttribute("value")).isEqualTo(""); File file = File.createTempFile("test", "txt"); file.deleteOnExit(); @@ -167,7 +160,7 @@ public void testShouldBeAbleToAlterTheContentsOfAFileUploadInputElement() throws uploadElement.sendKeys(file.getAbsolutePath()); String uploadPath = uploadElement.getAttribute("value"); - assertTrue(uploadPath.endsWith(file.getName())); + assertThat(uploadPath.endsWith(file.getName())).isTrue(); } @Test @@ -179,7 +172,7 @@ public void testShouldBeAbleToSendKeysToAFileUploadInputElementInAnXhtmlDocument driver.get(pages.xhtmlFormPage); WebElement uploadElement = driver.findElement(By.id("file")); - assertThat(uploadElement.getAttribute("value"), equalTo("")); + assertThat(uploadElement.getAttribute("value")).isEqualTo(""); File file = File.createTempFile("test", "txt"); file.deleteOnExit(); @@ -187,7 +180,7 @@ public void testShouldBeAbleToSendKeysToAFileUploadInputElementInAnXhtmlDocument uploadElement.sendKeys(file.getAbsolutePath()); String uploadPath = uploadElement.getAttribute("value"); - assertTrue(uploadPath.endsWith(file.getName())); + assertThat(uploadPath.endsWith(file.getName())).isTrue(); } @Test @@ -198,14 +191,14 @@ public void testShouldBeAbleToUploadTheSameFileTwice() throws IOException { driver.get(pages.formPage); WebElement uploadElement = driver.findElement(By.id("upload")); - assertThat(uploadElement.getAttribute("value"), equalTo("")); + assertThat(uploadElement.getAttribute("value")).isEqualTo(""); uploadElement.sendKeys(file.getAbsolutePath()); uploadElement.submit(); driver.get(pages.formPage); uploadElement = driver.findElement(By.id("upload")); - assertThat(uploadElement.getAttribute("value"), equalTo("")); + assertThat(uploadElement.getAttribute("value")).isEqualTo(""); uploadElement.sendKeys(file.getAbsolutePath()); uploadElement.submit(); @@ -219,11 +212,11 @@ public void testSendingKeyboardEventsShouldAppendTextInInputs() { WebElement element = driver.findElement(By.id("working")); element.sendKeys("some"); String value = element.getAttribute("value"); - assertThat(value, is("some")); + assertThat(value).isEqualTo("some"); element.sendKeys(" text"); value = element.getAttribute("value"); - assertThat(value, is("some text")); + assertThat(value).isEqualTo("some text"); } @Test @@ -234,7 +227,7 @@ public void testSendingKeyboardEventsShouldAppendTextInInputsWithExistingValue() element.sendKeys(". Some text"); String value = element.getAttribute("value"); - assertThat(value, is("Example text. Some text")); + assertThat(value).isEqualTo("Example text. Some text"); } @Test @@ -246,18 +239,19 @@ public void testSendingKeyboardEventsShouldAppendTextInTextAreas() { element.sendKeys(". Some text"); String value = element.getAttribute("value"); - assertThat(value, is("Example text. Some text")); + assertThat(value).isEqualTo("Example text. Some text"); } @Test public void testEmptyTextBoxesShouldReturnAnEmptyStringNotNull() { driver.get(pages.formPage); WebElement emptyTextBox = driver.findElement(By.id("working")); - assertEquals(emptyTextBox.getAttribute("value"), ""); + assertThat(emptyTextBox.getAttribute("value")).isEqualTo(""); } @Test @Ignore(value = SAFARI, reason = "Does not support alerts yet") + @Ignore(value = MARIONETTE, reason = "https://bugzilla.mozilla.org/show_bug.cgi?id=1487705") public void handleFormWithJavascriptAction() { String url = appServer.whereIs("form_handling_js_submit.html"); driver.get(url); @@ -267,7 +261,7 @@ public void handleFormWithJavascriptAction() { String text = alert.getText(); alert.accept(); - assertEquals("Tasty cheese", text); + assertThat(text).isEqualTo("Tasty cheese"); } @Test @@ -333,6 +327,6 @@ private void checkSubmitButton(String buttonId) { wait.until(titleIs("Submitted Successfully!")); - assertThat(driver.getCurrentUrl(), containsString("name="+name)); + assertThat(driver.getCurrentUrl()).contains("name="+name); } } diff --git a/java/client/test/org/openqa/selenium/FrameSwitchingTest.java b/java/client/test/org/openqa/selenium/FrameSwitchingTest.java index b9c146efcf21b..df4558f3c87aa 100644 --- a/java/client/test/org/openqa/selenium/FrameSwitchingTest.java +++ b/java/client/test/org/openqa/selenium/FrameSwitchingTest.java @@ -17,13 +17,8 @@ package org.openqa.selenium; -import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.instanceOf; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assume.assumeFalse; import static org.openqa.selenium.support.ui.ExpectedConditions.frameToBeAvailableAndSwitchToIt; import static org.openqa.selenium.support.ui.ExpectedConditions.not; @@ -35,7 +30,6 @@ import static org.openqa.selenium.testing.Driver.IE; import static org.openqa.selenium.testing.Driver.MARIONETTE; import static org.openqa.selenium.testing.Driver.SAFARI; -import static org.openqa.selenium.testing.TestUtilities.catchThrowable; import org.junit.After; import org.junit.Test; @@ -104,7 +98,7 @@ public void testShouldBeAbleToSwitchToAFrameByItsIndex() { driver.get(pages.framesetPage); driver.switchTo().frame(1); - assertThat(driver.findElement(By.id("pageNumber")).getText(), equalTo("2")); + assertThat(driver.findElement(By.id("pageNumber")).getText()).isEqualTo("2"); } @Test @@ -112,7 +106,7 @@ public void testShouldBeAbleToSwitchToAnIframeByItsIndex() { driver.get(pages.iframePage); driver.switchTo().frame(0); - assertThat(driver.findElement(By.name("id-name1")).getAttribute("value"), equalTo("name")); + assertThat(driver.findElement(By.name("id-name1")).getAttribute("value")).isEqualTo("name"); } @Test @@ -120,7 +114,7 @@ public void testShouldBeAbleToSwitchToAFrameByItsName() { driver.get(pages.framesetPage); driver.switchTo().frame("fourth"); - assertThat(driver.findElement(By.tagName("frame")).getAttribute("name"), equalTo("child1")); + assertThat(driver.findElement(By.tagName("frame")).getAttribute("name")).isEqualTo("child1"); } @Test @@ -128,14 +122,14 @@ public void testShouldBeAbleToSwitchToAnIframeByItsName() { driver.get(pages.iframePage); driver.switchTo().frame("iframe1-name"); - assertThat(driver.findElement(By.name("id-name1")).getAttribute("value"), equalTo("name")); + assertThat(driver.findElement(By.name("id-name1")).getAttribute("value")).isEqualTo("name"); } @Test public void testShouldBeAbleToSwitchToAFrameByItsID() { driver.get(pages.framesetPage); driver.switchTo().frame("fifth"); - assertThat(driver.findElement(By.name("windowOne")).getText(), equalTo("Open new window")); + assertThat(driver.findElement(By.name("windowOne")).getText()).isEqualTo("Open new window"); } @Test @@ -143,14 +137,14 @@ public void testShouldBeAbleToSwitchToAnIframeByItsID() { driver.get(pages.iframePage); driver.switchTo().frame("iframe1"); - assertThat(driver.findElement(By.name("id-name1")).getAttribute("value"), equalTo("name")); + assertThat(driver.findElement(By.name("id-name1")).getAttribute("value")).isEqualTo("name"); } @Test public void testShouldBeAbleToSwitchToFrameWithNameContainingDot() { driver.get(pages.framesetPage); driver.switchTo().frame("sixth.iframe1"); - assertThat(driver.findElement(By.tagName("body")).getText(), containsString("Page number 3")); + assertThat(driver.findElement(By.tagName("body")).getText()).contains("Page number 3"); } @Test @@ -159,7 +153,7 @@ public void testShouldBeAbleToSwitchToAFrameUsingAPreviouslyLocatedWebElement() WebElement frame = driver.findElement(By.tagName("frame")); driver.switchTo().frame(frame); - assertThat(driver.findElement(By.id("pageNumber")).getText(), equalTo("1")); + assertThat(driver.findElement(By.id("pageNumber")).getText()).isEqualTo("1"); } @Test @@ -169,7 +163,7 @@ public void testShouldBeAbleToSwitchToAnIFrameUsingAPreviouslyLocatedWebElement( driver.switchTo().frame(frame); WebElement element = driver.findElement(By.name("id-name1")); - assertThat(element.getAttribute("value"), equalTo("name")); + assertThat(element.getAttribute("value")).isEqualTo("name"); } @Test @@ -177,8 +171,8 @@ public void testShouldEnsureElementIsAFrameBeforeSwitching() { driver.get(pages.framesetPage); WebElement frame = driver.findElement(By.tagName("frameset")); - Throwable t = catchThrowable(() -> driver.switchTo().frame(frame)); - assertThat(t, instanceOf(NoSuchFrameException.class)); + assertThatExceptionOfType(NoSuchFrameException.class) + .isThrownBy(() -> driver.switchTo().frame(frame)); } @Test @@ -186,20 +180,20 @@ public void testFrameSearchesShouldBeRelativeToTheCurrentlySelectedFrame() { driver.get(pages.framesetPage); driver.switchTo().frame("second"); - assertThat(driver.findElement(By.id("pageNumber")).getText(), equalTo("2")); + assertThat(driver.findElement(By.id("pageNumber")).getText()).isEqualTo("2"); - Throwable t = catchThrowable(() -> driver.switchTo().frame("third")); - assertThat(t, instanceOf(NoSuchFrameException.class)); + assertThatExceptionOfType(NoSuchFrameException.class) + .isThrownBy(() -> driver.switchTo().frame("third")); driver.switchTo().defaultContent(); driver.switchTo().frame("third"); - Throwable t2 = catchThrowable(() -> driver.switchTo().frame("second")); - assertThat(t2, instanceOf(NoSuchFrameException.class)); + assertThatExceptionOfType(NoSuchFrameException.class) + .isThrownBy(() -> driver.switchTo().frame("second")); driver.switchTo().defaultContent(); driver.switchTo().frame("second"); - assertThat(driver.findElement(By.id("pageNumber")).getText(), equalTo("2")); + assertThat(driver.findElement(By.id("pageNumber")).getText()).isEqualTo("2"); } @Test @@ -207,7 +201,7 @@ public void testShouldSelectChildFramesByChainedCalls() { driver.get(pages.framesetPage); driver.switchTo().frame("fourth").switchTo().frame("child2"); - assertThat(driver.findElement(By.id("pageNumber")).getText(), equalTo("11")); + assertThat(driver.findElement(By.id("pageNumber")).getText()).isEqualTo("11"); } @Test @@ -215,24 +209,24 @@ public void testShouldThrowFrameNotFoundExceptionLookingUpSubFramesWithSuperFram driver.get(pages.framesetPage); driver.switchTo().frame("fourth"); - Throwable t = catchThrowable(() -> driver.switchTo().frame("second")); - assertThat(t, instanceOf(NoSuchFrameException.class)); + assertThatExceptionOfType(NoSuchFrameException.class) + .isThrownBy(() -> driver.switchTo().frame("second")); } @Test public void testShouldThrowAnExceptionWhenAFrameCannotBeFound() { driver.get(pages.xhtmlTestPage); - Throwable t = catchThrowable(() -> driver.switchTo().frame("Nothing here")); - assertThat(t, instanceOf(NoSuchFrameException.class)); + assertThatExceptionOfType(NoSuchFrameException.class) + .isThrownBy(() -> driver.switchTo().frame("Nothing here")); } @Test public void testShouldThrowAnExceptionWhenAFrameCannotBeFoundByIndex() { driver.get(pages.xhtmlTestPage); - Throwable t = catchThrowable(() -> driver.switchTo().frame(27)); - assertThat(t, instanceOf(NoSuchFrameException.class)); + assertThatExceptionOfType(NoSuchFrameException.class) + .isThrownBy(() -> driver.switchTo().frame(27)); } @Test @@ -241,7 +235,7 @@ public void testShouldBeAbleToSwitchToParentFrame() { driver.get(pages.framesetPage); driver.switchTo().frame("fourth").switchTo().parentFrame().switchTo().frame("first"); - assertThat(driver.findElement(By.id("pageNumber")).getText(), equalTo("1")); + assertThat(driver.findElement(By.id("pageNumber")).getText()).isEqualTo("1"); } @Test @@ -251,7 +245,7 @@ public void testShouldBeAbleToSwitchToParentFrameFromASecondLevelFrame() { driver.switchTo().frame("fourth").switchTo().frame("child1") .switchTo().parentFrame().switchTo().frame("child2"); - assertThat(driver.findElement(By.id("pageNumber")).getText(), equalTo("11")); + assertThat(driver.findElement(By.id("pageNumber")).getText()).isEqualTo("11"); } @Test @@ -260,7 +254,7 @@ public void testShouldBeAbleToSwitchToParentFrameFromASecondLevelFrame() { public void testSwitchingToParentFrameFromDefaultContextIsNoOp() { driver.get(pages.xhtmlTestPage); driver.switchTo().parentFrame(); - assertEquals(driver.getTitle(), "XHTML Test Page"); + assertThat(driver.getTitle()).isEqualTo("XHTML Test Page"); } @Test @@ -325,7 +319,7 @@ public void testShouldAllowTheUserToSwitchToAnIFrameAndRemainFocusedOnIt() { driver.findElement(By.id("submitButton")).click(); - assertThat(getTextOfGreetingElement(), equalTo("Success!")); + assertThat(getTextOfGreetingElement()).isEqualTo("Success!"); } public String getTextOfGreetingElement() { @@ -340,10 +334,10 @@ public void testShouldBeAbleToClickInAFrame() { // This should replace frame "third" ... driver.findElement(By.id("submitButton")).click(); // driver should still be focused on frame "third" ... - assertThat(getTextOfGreetingElement(), equalTo("Success!")); + assertThat(getTextOfGreetingElement()).isEqualTo("Success!"); // Make sure it was really frame "third" which was replaced ... driver.switchTo().defaultContent().switchTo().frame("third"); - assertThat(getTextOfGreetingElement(), equalTo("Success!")); + assertThat(getTextOfGreetingElement()).isEqualTo("Success!"); } @Test @@ -364,12 +358,12 @@ public void testShouldBeAbleToClickInASubFrame() { // This should replace frame "iframe1" inside frame "sixth" ... driver.findElement(By.id("submitButton")).click(); // driver should still be focused on frame "iframe1" inside frame "sixth" ... - assertThat(getTextOfGreetingElement(), equalTo("Success!")); + assertThat(getTextOfGreetingElement()).isEqualTo("Success!"); // Make sure it was really frame "iframe1" inside frame "sixth" which was replaced ... driver.switchTo().defaultContent() .switchTo().frame("sixth") .switchTo().frame("iframe1"); - assertThat(driver.findElement(By.id("greeting")).getText(), equalTo("Success!")); + assertThat(driver.findElement(By.id("greeting")).getText()).isEqualTo("Success!"); } @Test @@ -380,27 +374,27 @@ public void testShouldBeAbleToFindElementsInIframesByXPath() { WebElement element = driver.findElement(By.xpath("//*[@id = 'changeme']")); - assertNotNull(element); + assertThat(element).isNotNull(); } @Test @Ignore(IE) public void testGetCurrentUrlReturnsTopLevelBrowsingContextUrl() { driver.get(pages.framesetPage); - assertThat(driver.getCurrentUrl(), equalTo(pages.framesetPage)); + assertThat(driver.getCurrentUrl()).isEqualTo(pages.framesetPage); driver.switchTo().frame("second"); - assertThat(driver.getCurrentUrl(), equalTo(pages.framesetPage)); + assertThat(driver.getCurrentUrl()).isEqualTo(pages.framesetPage); } @Test @Ignore(IE) public void testGetCurrentUrlReturnsTopLevelBrowsingContextUrlForIframes() { driver.get(pages.iframePage); - assertThat(driver.getCurrentUrl(), equalTo(pages.iframePage)); + assertThat(driver.getCurrentUrl()).isEqualTo(pages.iframePage); driver.switchTo().frame("iframe1"); - assertThat(driver.getCurrentUrl(), equalTo(pages.iframePage)); + assertThat(driver.getCurrentUrl()).isEqualTo(pages.iframePage); } @Test @@ -472,15 +466,15 @@ public void testShouldNotBeAbleToDoAnythingTheFrameIsDeletedFromUnderUs() { driver.switchTo().frame("iframe1"); driver.findElement(By.id("killIframe")).click(); - Throwable t = catchThrowable(() -> driver.findElement(By.id("killIframe"))); - assertThat(t, instanceOf(NoSuchFrameException.class)); + assertThatExceptionOfType(NoSuchFrameException.class) + .isThrownBy(() -> driver.findElement(By.id("killIframe"))); } @Test public void testShouldReturnWindowTitleInAFrameset() { driver.get(pages.framesetPage); driver.switchTo().frame("third"); - assertEquals("Unique title", driver.getTitle()); + assertThat(driver.getTitle()).isEqualTo("Unique title"); } @Test @@ -488,9 +482,9 @@ public void testJavaScriptShouldExecuteInTheContextOfTheCurrentFrame() { JavascriptExecutor executor = (JavascriptExecutor) driver; driver.get(pages.framesetPage); - assertTrue((Boolean) executor.executeScript("return window == window.top")); + assertThat((Boolean) executor.executeScript("return window == window.top")).isTrue(); driver.switchTo().frame("third"); - assertTrue((Boolean) executor.executeScript("return window != window.top")); + assertThat((Boolean) executor.executeScript("return window != window.top")).isTrue(); } @Test @@ -515,7 +509,7 @@ public void testShouldNotSwitchMagicallyToTheTopWindow() { if (url.endsWith("?")) { url = url.substring(0, url.length()-1); } - assertEquals(baseUrl + "bug4876_iframe.html", url); + assertThat(url).isEqualTo(baseUrl + "bug4876_iframe.html"); } } } diff --git a/java/client/test/org/openqa/selenium/I18nTest.java b/java/client/test/org/openqa/selenium/I18nTest.java index 834f56b705bc9..aeecf781dada0 100644 --- a/java/client/test/org/openqa/selenium/I18nTest.java +++ b/java/client/test/org/openqa/selenium/I18nTest.java @@ -17,9 +17,7 @@ package org.openqa.selenium; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assume.assumeFalse; import static org.junit.Assume.assumeTrue; import static org.openqa.selenium.testing.Driver.CHROME; @@ -37,7 +35,6 @@ import org.openqa.selenium.testing.NotYetImplemented; import org.openqa.selenium.testing.TestUtilities; -import java.util.Arrays; import java.util.List; public class I18nTest extends JUnit4TestBase { @@ -72,7 +69,7 @@ public void testEnteringHebrewTextFromLeftToRight() { input.sendKeys(shalom); - assertEquals(shalom, input.getAttribute("value")); + assertThat(input.getAttribute("value")).isEqualTo(shalom); } @Test @@ -82,7 +79,7 @@ public void testEnteringHebrewTextFromRightToLeft() { input.sendKeys(tmunot); - assertEquals(tmunot, input.getAttribute("value")); + assertThat(input.getAttribute("value")).isEqualTo(tmunot); } @Test @@ -104,7 +101,7 @@ public void testEnteringSupplementaryCharacters() { WebElement el = driver.findElement(By.name("i18n")); el.sendKeys(input); - assertEquals(input, el.getAttribute("value")); + assertThat(el.getAttribute("value")).isEqualTo(input); } @NeedsFreshDriver @@ -117,7 +114,7 @@ public void testShouldBeAbleToReturnTheTextInAPage() { String text = driver.findElement(By.tagName("body")).getText(); - assertEquals(shalom, text); + assertThat(text).isEqualTo(shalom); } @NeedsFreshDriver @@ -153,8 +150,8 @@ public void testShouldBeAbleToActivateIMEEngine() throws InterruptedException { Thread.sleep(500); totalWaits++; } - assertTrue("IME Engine should be activated.", ime.isActivated()); - assertEquals(desiredEngine, ime.getActiveEngine()); + assertThat(ime.isActivated()).isTrue(); + assertThat(ime.getActiveEngine()).isEqualTo(desiredEngine); // Send the Romaji for "Tokyo". The space at the end instructs the IME to convert the word. input.sendKeys("toukyou "); @@ -163,12 +160,13 @@ public void testShouldBeAbleToActivateIMEEngine() throws InterruptedException { String elementValue = input.getAttribute("value"); ime.deactivate(); - assertFalse("IME engine should be off.", ime.isActivated()); + assertThat(ime.isActivated()).isFalse(); // IME is not present. Don't fail because of that. But it should have the Romaji value // instead. - assertTrue("The elemnt's value should either remain in Romaji or be converted properly." - + " It was:" + elementValue, elementValue.equals(tokyo)); + assertThat(elementValue) + .describedAs("The elemnt's value should either remain in Romaji or be converted properly.") + .isEqualTo(tokyo); } @Test @@ -195,9 +193,9 @@ public void testShouldBeAbleToInputJapanese() { // IME is not present. Don't fail because of that. But it should have the Romaji value // instead. - String[] possibleValues = {tokyo, "\uE040" + "toukyou ", "toukyou "}; - assertTrue("The element's value should either remain in Romaji or be converted properly." - + " It was: -" + elementValue + "-", Arrays.asList(possibleValues).contains(elementValue)); + assertThat(elementValue) + .describedAs("The element's value should either remain in Romaji or be converted properly.") + .isIn(tokyo, "\uE040" + "toukyou ", "toukyou "); } } diff --git a/java/client/test/org/openqa/selenium/ImmutableCapabilitiesTest.java b/java/client/test/org/openqa/selenium/ImmutableCapabilitiesTest.java index a3d47426519ff..f175881688806 100644 --- a/java/client/test/org/openqa/selenium/ImmutableCapabilitiesTest.java +++ b/java/client/test/org/openqa/selenium/ImmutableCapabilitiesTest.java @@ -17,65 +17,63 @@ package org.openqa.selenium; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; +import static org.assertj.core.api.Assertions.assertThat; import com.google.common.collect.ImmutableMap; import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; -@RunWith(JUnit4.class) public class ImmutableCapabilitiesTest { @Test public void canCreateEmptyCapabilities() { - Capabilities empty = new ImmutableCapabilities(); - assertEquals(empty.asMap(), ImmutableMap.of()); + Capabilities caps = new ImmutableCapabilities(); + assertThat(caps.asMap()).isEqualTo(ImmutableMap.of()); } @Test public void canCreateSinglePairCapabilities() { - Capabilities empty = new ImmutableCapabilities("c1", "v1"); - assertEquals(empty.asMap(), ImmutableMap.of("c1", "v1")); + Capabilities caps = new ImmutableCapabilities("c1", "v1"); + assertThat(caps.asMap()).isEqualTo(ImmutableMap.of("c1", "v1")); } @Test public void canCreateTwoPairCapabilities() { - Capabilities empty = new ImmutableCapabilities("c1", "v1", "c2", 2); - assertEquals(empty.asMap(), ImmutableMap.of("c1", "v1", "c2", 2)); + Capabilities caps = new ImmutableCapabilities("c1", "v1", "c2", 2); + assertThat(caps.asMap()).isEqualTo(ImmutableMap.of("c1", "v1", "c2", 2)); } @Test public void canCreateThreePairCapabilities() { - Capabilities empty = new ImmutableCapabilities("c1", "v1", "c2", 2, "c3", true); - assertEquals(empty.asMap(), ImmutableMap.of("c1", "v1", "c2", 2, "c3", true)); + Capabilities caps = new ImmutableCapabilities("c1", "v1", "c2", 2, "c3", true); + assertThat(caps.asMap()).isEqualTo(ImmutableMap.of("c1", "v1", "c2", 2, "c3", true)); } @Test public void canCreateFourPairCapabilities() { - Capabilities empty = new ImmutableCapabilities("c1", "v1", "c2", 2, "c3", true, "c4", "v4"); - assertEquals(empty.asMap(), ImmutableMap.of("c1", "v1", "c2", 2, "c3", true, "c4", "v4")); + Capabilities caps = new ImmutableCapabilities("c1", "v1", "c2", 2, "c3", true, "c4", "v4"); + assertThat(caps.asMap()) + .isEqualTo(ImmutableMap.of("c1", "v1", "c2", 2, "c3", true, "c4", "v4")); } @Test public void canCreateFivePairCapabilities() { - Capabilities empty = new ImmutableCapabilities("c1", "v1", "c2", 2, "c3", true, "c4", "v4", "c5", "v5"); - assertEquals(empty.asMap(), ImmutableMap.of("c1", "v1", "c2", 2, "c3", true, "c4", "v4", "c5", "v5")); + Capabilities caps = new ImmutableCapabilities("c1", "v1", "c2", 2, "c3", true, "c4", "v4", "c5", "v5"); + assertThat(caps.asMap()) + .isEqualTo(ImmutableMap.of("c1", "v1", "c2", 2, "c3", true, "c4", "v4", "c5", "v5")); } @Test public void canCompareCapabilities() { MutableCapabilities caps1 = new MutableCapabilities(); MutableCapabilities caps2 = new MutableCapabilities(); - assertEquals(new ImmutableCapabilities(caps1), new ImmutableCapabilities(caps2)); + assertThat(new ImmutableCapabilities(caps2)).isEqualTo(new ImmutableCapabilities(caps1)); caps1.setCapability("xxx", "yyy"); - assertNotEquals(new ImmutableCapabilities(caps1), new ImmutableCapabilities(caps2)); + assertThat(new ImmutableCapabilities(caps1)).isNotEqualTo(new ImmutableCapabilities(caps2)); caps2.setCapability("xxx", "yyy"); - assertEquals(new ImmutableCapabilities(caps1), new ImmutableCapabilities(caps2)); + assertThat(new ImmutableCapabilities(caps2)).isEqualTo(new ImmutableCapabilities(caps1)); } } diff --git a/java/client/test/org/openqa/selenium/ImplicitWaitTest.java b/java/client/test/org/openqa/selenium/ImplicitWaitTest.java index 3586ec47c8051..d988806aef3c0 100644 --- a/java/client/test/org/openqa/selenium/ImplicitWaitTest.java +++ b/java/client/test/org/openqa/selenium/ImplicitWaitTest.java @@ -17,16 +17,13 @@ package org.openqa.selenium; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static java.util.concurrent.TimeUnit.MILLISECONDS; import static java.util.concurrent.TimeUnit.SECONDS; -import static org.hamcrest.Matchers.instanceOf; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; import static org.openqa.selenium.testing.Driver.IE; import static org.openqa.selenium.testing.Driver.MARIONETTE; import static org.openqa.selenium.testing.Driver.SAFARI; -import static org.openqa.selenium.testing.TestUtilities.catchThrowable; import org.junit.After; import org.junit.Before; @@ -70,8 +67,8 @@ public void testShouldImplicitlyWaitForASingleElement() { public void testShouldStillFailToFindAnElementWhenImplicitWaitsAreEnabled() { driver.get(pages.dynamicPage); driver.manage().timeouts().implicitlyWait(500, MILLISECONDS); - Throwable t = catchThrowable(() -> driver.findElement(By.id("box0"))); - assertThat(t, instanceOf(NoSuchElementException.class)); + assertThatExceptionOfType(NoSuchElementException.class) + .isThrownBy(() -> driver.findElement(By.id("box0"))); } @Test @@ -79,8 +76,8 @@ public void testShouldReturnAfterFirstAttemptToFindOneAfterDisablingImplicitWait driver.get(pages.dynamicPage); driver.manage().timeouts().implicitlyWait(3000, MILLISECONDS); driver.manage().timeouts().implicitlyWait(0, MILLISECONDS); - Throwable t = catchThrowable(() -> driver.findElement(By.id("box0"))); - assertThat(t, instanceOf(NoSuchElementException.class)); + assertThatExceptionOfType(NoSuchElementException.class) + .isThrownBy(() -> driver.findElement(By.id("box0"))); } @Test @@ -93,7 +90,7 @@ public void testShouldImplicitlyWaitUntilAtLeastOneElementIsFoundWhenSearchingFo add.click(); List elements = driver.findElements(By.className("redbox")); - assertFalse(elements.isEmpty()); + assertThat(elements).isNotEmpty(); } @Test @@ -101,7 +98,7 @@ public void testShouldStillFailToFindElementsWhenImplicitWaitsAreEnabled() { driver.get(pages.dynamicPage); driver.manage().timeouts().implicitlyWait(500, MILLISECONDS); List elements = driver.findElements(By.className("redbox")); - assertTrue(elements.isEmpty()); + assertThat(elements).isEmpty(); } @Test @@ -109,7 +106,7 @@ public void testShouldStillFailToFindElementsByIdWhenImplicitWaitsAreEnabled() { driver.get(pages.dynamicPage); driver.manage().timeouts().implicitlyWait(500, MILLISECONDS); List elements = driver.findElements(By.id("redbox")); - assertTrue(elements.toString(), elements.isEmpty()); + assertThat(elements).isEmpty(); } @Test @@ -122,7 +119,7 @@ public void testShouldReturnAfterFirstAttemptToFindManyAfterDisablingImplicitWai add.click(); List elements = driver.findElements(By.className("redbox")); - assertTrue(elements.isEmpty()); + assertThat(elements).isEmpty(); } @Test @@ -136,7 +133,7 @@ public void testShouldImplicitlyWaitForAnElementToBeVisibleBeforeInteracting() { WebElement revealed = driver.findElement(By.id("revealed")); driver.manage().timeouts().implicitlyWait(5000, MILLISECONDS); - assertFalse("revealed should not be visible", revealed.isDisplayed()); + assertThat(revealed.isDisplayed()).isTrue(); reveal.click(); revealed.sendKeys("hello world"); } @@ -163,7 +160,7 @@ public void testShouldRetainImplicitlyWaitFromTheReturnedWebDriverOfFrameSwitchT long time = end - start; - assertTrue(time >= 1000); + assertThat(time).isGreaterThanOrEqualTo(1000); } } diff --git a/java/client/test/org/openqa/selenium/JavascriptEnabledDriverTest.java b/java/client/test/org/openqa/selenium/JavascriptEnabledDriverTest.java index bad3eaf555d21..13d7395f2cf88 100644 --- a/java/client/test/org/openqa/selenium/JavascriptEnabledDriverTest.java +++ b/java/client/test/org/openqa/selenium/JavascriptEnabledDriverTest.java @@ -17,12 +17,7 @@ package org.openqa.selenium; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assume.assumeTrue; import static org.openqa.selenium.WaitingConditions.elementTextToEqual; import static org.openqa.selenium.WaitingConditions.elementValueToEqual; @@ -31,7 +26,6 @@ import static org.openqa.selenium.support.ui.ExpectedConditions.titleIs; import static org.openqa.selenium.testing.Driver.SAFARI; -import org.hamcrest.Matchers; import org.junit.Test; import org.openqa.selenium.interactions.Locatable; import org.openqa.selenium.support.ui.ExpectedConditions; @@ -45,10 +39,10 @@ public class JavascriptEnabledDriverTest extends JUnit4TestBase { public void testDocumentShouldReflectLatestTitle() { driver.get(pages.javascriptPage); - assertThat(driver.getTitle(), equalTo("Testing Javascript")); + assertThat(driver.getTitle()).isEqualTo("Testing Javascript"); driver.findElement(By.linkText("Change the page title!")).click(); waitForTitleChange("Changed"); - assertThat(driver.getTitle(), equalTo("Changed")); + assertThat(driver.getTitle()).isEqualTo("Changed"); } @Test @@ -56,7 +50,7 @@ public void testDocumentShouldReflectLatestTitle() { public void testDocumentShouldReflectLatestDom() { driver.get(pages.javascriptPage); String currentText = driver.findElement(By.xpath("//div[@id='dynamo']")).getText(); - assertThat(currentText, equalTo("What's for dinner?")); + assertThat(currentText).isEqualTo("What's for dinner?"); WebElement webElement = driver.findElement(By.linkText("Update a div")); webElement.click(); @@ -64,7 +58,7 @@ public void testDocumentShouldReflectLatestDom() { WebElement dynamo = driver.findElement(By.xpath("//div[@id='dynamo']")); wait.until(elementTextToEqual(dynamo, "Fish and chips!")); - assertThat(dynamo.getText(), equalTo("Fish and chips!")); + assertThat(dynamo.getText()).isEqualTo("Fish and chips!"); } @Test @@ -74,7 +68,7 @@ public void testShouldWaitForLoadsToCompleteAfterJavascriptCausesANewPageToLoad( driver.findElement(By.id("changeme")).click(); waitForTitleChange("Page3"); - assertThat(driver.getTitle(), equalTo("Page3")); + assertThat(driver.getTitle()).isEqualTo("Page3"); } @Test @@ -84,7 +78,7 @@ public void testShouldBeAbleToFindElementAfterJavascriptCausesANewPageToLoad() { driver.findElement(By.id("changeme")).click(); waitForTitleChange("Page3"); - assertThat(driver.findElement(By.id("pageNumber")).getText(), equalTo("3")); + assertThat(driver.findElement(By.id("pageNumber")).getText()).isEqualTo("3"); } @Test @@ -94,7 +88,7 @@ public void testShouldFireOnChangeEventWhenSettingAnElementsValue() { driver.findElement(By.id("change")).sendKeys("foo"); String result = driver.findElement(By.id("result")).getText(); - assertThat(result, equalTo("change")); + assertThat(result).isEqualTo("change"); } @Test @@ -105,7 +99,7 @@ public void testShouldBeAbleToSubmitFormsByCausingTheOnClickEventToFire() { waitForTitleChange("We Arrive Here"); - assertThat(driver.getTitle(), is("We Arrive Here")); + assertThat(driver.getTitle()).isEqualTo("We Arrive Here"); } private void waitForTitleChange(String newTitle) { @@ -120,20 +114,20 @@ public void testShouldBeAbleToClickOnSubmitButtons() { waitForTitleChange("We Arrive Here"); - assertThat(driver.getTitle(), is("We Arrive Here")); + assertThat(driver.getTitle()).isEqualTo("We Arrive Here"); } @Test public void testIssue80ClickShouldGenerateClickEvent() { driver.get(pages.javascriptPage); WebElement element = driver.findElement(By.id("clickField")); - assertEquals("Hello", element.getAttribute("value")); + assertThat(element.getAttribute("value")).isEqualTo("Hello"); element.click(); String elementValue = wait.until(elementValueToEqual(element, "Clicked")); - assertEquals("Clicked", elementValue); + assertThat(elementValue).isEqualTo("Clicked"); } @Test @@ -143,7 +137,7 @@ public void testShouldBeAbleToSwitchToFocusedElement() { driver.findElement(By.id("switchFocus")).click(); WebElement element = driver.switchTo().activeElement(); - assertThat(element.getAttribute("id"), is("theworks")); + assertThat(element.getAttribute("id")).isEqualTo("theworks"); } @Test @@ -152,7 +146,7 @@ public void testIfNoElementHasFocusTheActiveElementIsTheBody() { WebElement element = driver.switchTo().activeElement(); - assertThat(element.getAttribute("name"), is("body")); + assertThat(element.getAttribute("name")).isEqualTo("body"); } @Test @@ -163,18 +157,16 @@ public void testChangeEventIsFiredAppropriatelyWhenFocusIsLost() { WebElement input = driver.findElement(By.id("changeable")); input.sendKeys("test"); moveFocus(); - assertThat(driver.findElement(By.id("result")).getText().trim(), - Matchers.either(is("focus change blur")).or(is("focus blur change"))); + assertThat(driver.findElement(By.id("result")).getText().trim()) + .isIn("focus change blur", "focus blur change"); input.sendKeys(Keys.BACK_SPACE, "t"); moveFocus(); // I weep. - assertThat(driver.findElement(By.id("result")).getText().trim(), - Matchers.either(is("focus change blur focus blur")) - .or(is("focus blur change focus blur")) - .or(is("focus blur change focus blur change")) - .or(is("focus change blur focus change blur"))); // What Chrome does + assertThat(driver.findElement(By.id("result")).getText().trim()) + .isIn("focus change blur focus blur", "focus blur change focus blur", + "focus blur change focus blur change", "focus change blur focus change blur"); } /** @@ -188,8 +180,7 @@ public void testShouldBeAbleToClickIfEvenSomethingHorribleHappens() { // If we get this far then the test has passed, but let's do something basic to prove the point String text = driver.findElement(By.id("error")).getText(); - - assertNotNull(text); + assertThat(text).isNotNull(); } @Test @@ -206,11 +197,9 @@ public void testShouldBeAbleToGetTheLocationOfAnElement() { Point point = ((Locatable) element).getCoordinates().inViewPort(); - assertTrue(String.format("Non-positive X coordinates: %d", point.getX()), - point.getX() > 1); + assertThat(point.getX()).as("X coordinate").isGreaterThan(1); // Element's Y coordinates can be 0, as the element is scrolled right to the top of the window. - assertTrue(String.format("Negative Y coordinates: %d", point.getY()), - point.getY() >= 0); + assertThat(point.getY()).as("Y coordinate").isGreaterThanOrEqualTo(0); } diff --git a/java/client/test/org/openqa/selenium/KeysTest.java b/java/client/test/org/openqa/selenium/KeysTest.java index 229d9c24da2e6..c4ebcd8c61c6a 100644 --- a/java/client/test/org/openqa/selenium/KeysTest.java +++ b/java/client/test/org/openqa/selenium/KeysTest.java @@ -17,56 +17,52 @@ package org.openqa.selenium; -import static org.hamcrest.Matchers.instanceOf; -import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotSame; -import static org.junit.Assert.assertThat; -import static org.openqa.selenium.testing.TestUtilities.catchThrowable; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.openqa.selenium.Keys.LEFT; +import static org.openqa.selenium.Keys.chord; +import static org.openqa.selenium.Keys.getKeyFromUnicode; import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; -@RunWith(JUnit4.class) public class KeysTest { @Test public void charAtPosition0ReturnsKeyCode() { - assertNotSame(Keys.LEFT.charAt(0), 0); + assertThat(Keys.LEFT.charAt(0)).isNotEqualTo(0); } @Test public void charAtOtherPositionReturnsZero() { - assertEquals(Keys.LEFT.charAt(10), 0); + assertThat(Keys.LEFT.charAt(10)).isEqualTo((char) 0); } @Test public void lengthIsAlwaysOne() { - assertThat(Keys.LEFT.length(), is(1)); + assertThat(LEFT.length()).isEqualTo(1); } @Test public void validSubSequence() { - assertEquals(Keys.LEFT.subSequence(0, 1), String.valueOf(Keys.LEFT)); + assertThat(String.valueOf(LEFT)).isEqualTo(LEFT.subSequence(0, 1)); } @Test public void invalidSubSequenceThrows() { - Throwable t = catchThrowable(() -> Keys.LEFT.subSequence(-1, 10)); - assertThat(t, instanceOf(IndexOutOfBoundsException.class)); + assertThatExceptionOfType(IndexOutOfBoundsException.class) + .isThrownBy(() -> LEFT.subSequence(-1, 10)); } @Test public void buildChord() { CharSequence[] sequences = {"foo", Keys.LEFT}; - assertEquals(Keys.chord(sequences), "foo\uE012\uE000"); + assertThat(chord(sequences)).isEqualTo("foo\uE012\uE000"); } @Test public void keyForCharacterCode() { Keys key = Keys.LEFT; - assertThat(Keys.getKeyFromUnicode(key.charAt(0)), is(key)); + assertThat((CharSequence) getKeyFromUnicode(key.charAt(0))).isEqualTo(key); } } diff --git a/java/client/test/org/openqa/selenium/MiscTest.java b/java/client/test/org/openqa/selenium/MiscTest.java index b3c0d7ffc27e7..06a56ede2c816 100644 --- a/java/client/test/org/openqa/selenium/MiscTest.java +++ b/java/client/test/org/openqa/selenium/MiscTest.java @@ -17,11 +17,7 @@ package org.openqa.selenium; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.openqa.selenium.testing.Driver.ALL; import static org.openqa.selenium.testing.Driver.CHROME; import static org.openqa.selenium.testing.Driver.IE; @@ -37,26 +33,26 @@ public class MiscTest extends JUnit4TestBase { @Test public void testShouldReturnTitleOfPageIfSet() { driver.get(pages.xhtmlTestPage); - assertThat(driver.getTitle(), equalTo(("XHTML Test Page"))); + assertThat(driver.getTitle()).isEqualTo(("XHTML Test Page")); driver.get(pages.simpleTestPage); - assertThat(driver.getTitle(), equalTo("Hello WebDriver")); + assertThat(driver.getTitle()).isEqualTo("Hello WebDriver"); } @Test public void testShouldReportTheCurrentUrlCorrectly() { driver.get(pages.simpleTestPage); - assertTrue(pages.simpleTestPage.equalsIgnoreCase(driver.getCurrentUrl())); + assertThat(driver.getCurrentUrl()).isEqualToIgnoringCase(pages.simpleTestPage); driver.get(pages.javascriptPage); - assertTrue(pages.javascriptPage.equalsIgnoreCase(driver.getCurrentUrl())); + assertThat(driver.getCurrentUrl()).isEqualToIgnoringCase(pages.javascriptPage); } @Test public void shouldReturnTagName() { driver.get(pages.formPage); WebElement selectBox = driver.findElement(By.id("cheese")); - assertThat(selectBox.getTagName().toLowerCase(), is("input")); + assertThat(selectBox.getTagName()).isEqualToIgnoringCase("input"); } @Test @@ -65,12 +61,8 @@ public void testShouldReturnTheSourceOfAPage() { String source = driver.getPageSource().toLowerCase(); - assertThat(source.contains("baz")); + assertThat(source).isEqualToIgnoringWhitespace("baz"); } @@ -101,11 +93,11 @@ public void testClickingShouldNotTrampleWOrHInGlobalScope() { driver.get(appServer.whereIs("globalscope.html")); String[] vars = new String[]{"w", "h"}; for (String var : vars) { - assertEquals(var, getGlobalVar(driver, var)); + assertThat(getGlobalVar(driver, var)).isEqualTo(var); } driver.findElement(By.id("toclick")).click(); for (String var : vars) { - assertEquals(var, getGlobalVar(driver, var)); + assertThat(getGlobalVar(driver, var)).isEqualTo(var); } } diff --git a/java/client/test/org/openqa/selenium/OutputTypeTest.java b/java/client/test/org/openqa/selenium/OutputTypeTest.java index e6b842c4951d6..19c86c359a168 100644 --- a/java/client/test/org/openqa/selenium/OutputTypeTest.java +++ b/java/client/test/org/openqa/selenium/OutputTypeTest.java @@ -16,32 +16,29 @@ // under the License. package org.openqa.selenium; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; +import static org.openqa.selenium.OutputType.BASE64; import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; import java.io.File; -@RunWith(JUnit4.class) public class OutputTypeTest { public static final String TEST_BASE64 = "ABADABAD"; public static final byte[] TEST_BYTES = new byte[] {0, 16, 3, 0, 16, 3}; @Test public void testBase64() { - assertEquals(TEST_BASE64, OutputType.BASE64.convertFromBase64Png(TEST_BASE64)); + assertThat(BASE64.convertFromBase64Png(TEST_BASE64)).isEqualTo(TEST_BASE64); } @Test public void testBytes() { byte[] bytes = OutputType.BYTES .convertFromBase64Png(TEST_BASE64); - assertEquals(TEST_BYTES.length, bytes.length); + assertThat(bytes.length).isEqualTo(TEST_BYTES.length); for (int i = 0; i < TEST_BYTES.length; i++) { - assertEquals("index " + i, TEST_BYTES[i], bytes[i]); + assertThat(TEST_BYTES[i]).as("index " + i).isEqualTo(bytes[i]); } } @@ -49,8 +46,8 @@ public void testBytes() { public void testFiles() { File tmpFile = OutputType.FILE .convertFromBase64Png(TEST_BASE64); - assertTrue(tmpFile.exists()); - assertEquals(TEST_BYTES.length, tmpFile.length()); + assertThat(tmpFile.exists()).isTrue(); + assertThat(tmpFile.length()).isEqualTo(TEST_BYTES.length); tmpFile.delete(); } } diff --git a/java/client/test/org/openqa/selenium/PageLoadingTest.java b/java/client/test/org/openqa/selenium/PageLoadingTest.java index 188317ef17f19..151437df2241d 100644 --- a/java/client/test/org/openqa/selenium/PageLoadingTest.java +++ b/java/client/test/org/openqa/selenium/PageLoadingTest.java @@ -17,15 +17,9 @@ package org.openqa.selenium; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static java.util.concurrent.TimeUnit.SECONDS; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.greaterThan; -import static org.hamcrest.Matchers.instanceOf; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.lessThan; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.junit.Assume.assumeFalse; import static org.openqa.selenium.Platform.ANDROID; @@ -42,9 +36,9 @@ import static org.openqa.selenium.testing.Driver.IE; import static org.openqa.selenium.testing.Driver.MARIONETTE; import static org.openqa.selenium.testing.Driver.SAFARI; -import static org.openqa.selenium.testing.TestUtilities.catchThrowable; import static org.openqa.selenium.testing.TestUtilities.getEffectivePlatform; import static org.openqa.selenium.testing.TestUtilities.isChrome; +import static org.openqa.selenium.testing.drivers.SauceDriver.shouldUseSauce; import org.junit.After; import org.junit.Test; @@ -57,7 +51,6 @@ import org.openqa.selenium.testing.NoDriverAfterTest; import org.openqa.selenium.testing.NotYetImplemented; import org.openqa.selenium.testing.SwitchToTopAfterTest; -import org.openqa.selenium.testing.drivers.SauceDriver; import org.openqa.selenium.testing.drivers.WebDriverBuilder; import java.util.Set; @@ -91,7 +84,7 @@ public void testNoneStrategyShouldNotWaitForPageToLoad() { long duration = end - start; // The slow loading resource on that page takes 6 seconds to return, // but with 'none' page loading strategy 'get' operation should not wait. - assertTrue("Took too long to load page: " + duration, duration < 1000); + assertThat(duration).as("Page loading duration").isLessThan(1000); } @Test @@ -114,7 +107,7 @@ public void testNoneStrategyShouldNotWaitForPageToRefresh() { long duration = end - start; // The slow loading resource on that page takes 6 seconds to return, // but with 'none' page loading strategy 'refresh' operation should not wait. - assertTrue("Took too long to load page: " + duration, duration < 1000); + assertThat(duration).as("Page loading duration").isLessThan(1000); } @Test @@ -137,7 +130,7 @@ public void testEagerStrategyShouldNotWaitForResources() { // The slow loading resource on that page takes 6 seconds to return. If we // waited for it, our load time should be over 6 seconds. long duration = end - start; - assertTrue("Took too long to load page: " + duration, duration < 5 * 1000); + assertThat(duration).as("Page loading duration").isLessThan(5 * 1000); } @Test @@ -163,7 +156,7 @@ public void testEagerStrategyShouldNotWaitForResourcesOnRefresh() { // The slow loading resource on that page takes 6 seconds to return. If we // waited for it, our load time should be over 6 seconds. long duration = end - start; - assertTrue("Took too long to refresh page: " + duration, duration < 5 * 1000); + assertThat(duration).as("Page loading duration").isLessThan(5 * 1000); } @Test @@ -182,13 +175,13 @@ public void testEagerStrategyShouldWaitForDocumentToBeLoaded() { @Test public void testNormalStrategyShouldWaitForDocumentToBeLoaded() { driver.get(pages.simpleTestPage); - assertThat(driver.getTitle(), equalTo("Hello WebDriver")); + assertThat(driver.getTitle()).isEqualTo("Hello WebDriver"); } @Test public void testShouldFollowRedirectsSentInTheHttpResponseHeaders() { driver.get(pages.redirectPage); - assertThat(driver.getTitle(), equalTo("We Arrive Here")); + assertThat(driver.getTitle()).isEqualTo("We Arrive Here"); } @Test @@ -223,9 +216,9 @@ public void testShouldReturnWhenGettingAUrlThatDoesNotResolve() { @Ignore(value = SAFARI) @NeedsFreshDriver public void testShouldThrowIfUrlIsMalformed() { - assumeFalse("Fails in Sauce Cloud", SauceDriver.shouldUseSauce()); - Throwable t = catchThrowable(() -> driver.get("www.test.com")); - assertThat(t, instanceOf(WebDriverException.class)); + assumeFalse("Fails in Sauce Cloud", shouldUseSauce()); + assertThatExceptionOfType(WebDriverException.class) + .isThrownBy(() -> driver.get("www.test.com")); } @Test @@ -233,9 +226,9 @@ public void testShouldThrowIfUrlIsMalformed() { @NotYetImplemented(value = SAFARI) @NeedsFreshDriver public void testShouldThrowIfUrlIsMalformedInPortPart() { - assumeFalse("Fails in Sauce Cloud", SauceDriver.shouldUseSauce()); - Throwable t = catchThrowable(() -> driver.get("http://localhost:3001bla")); - assertThat(t, instanceOf(WebDriverException.class)); + assumeFalse("Fails in Sauce Cloud", shouldUseSauce()); + assertThatExceptionOfType(WebDriverException.class) + .isThrownBy(() -> driver.get("http://localhost:3001bla")); } @Test @@ -251,7 +244,7 @@ public void testShouldReturnWhenGettingAUrlThatDoesNotConnect() { public void testShouldReturnURLOnNotExistedPage() { String url = appServer.whereIs("not_existed_page.html"); driver.get(url); - assertEquals(url, driver.getCurrentUrl()); + assertThat(driver.getCurrentUrl()).isEqualTo(url); } @SwitchToTopAfterTest @@ -261,11 +254,11 @@ public void testShouldBeAbleToLoadAPageWithFramesetsAndWaitUntilAllFramesAreLoad driver.switchTo().frame(0); WebElement pageNumber = driver.findElement(By.xpath("//span[@id='pageNumber']")); - assertThat(pageNumber.getText().trim(), equalTo("1")); + assertThat(pageNumber.getText().trim()).isEqualTo("1"); driver.switchTo().defaultContent().switchTo().frame(1); pageNumber = driver.findElement(By.xpath("//span[@id='pageNumber']")); - assertThat(pageNumber.getText().trim(), equalTo("2")); + assertThat(pageNumber.getText().trim()).isEqualTo("2"); } @NeedsFreshDriver @@ -291,7 +284,7 @@ public void testShouldDoNothingIfThereIsNothingToGoBackTo() { driver.navigate().back(); wait.until(titleIs(originalTitle)); driver.navigate().back(); // Nothing to go back to, must stay. - assertThat(driver.getTitle(), equalTo(originalTitle)); + assertThat(driver.getTitle()).isEqualTo(originalTitle); } @Test @@ -346,7 +339,7 @@ public void testShouldBeAbleToRefreshAPage() { driver.navigate().refresh(); - assertThat(driver.getTitle(), equalTo("XHTML Test Page")); + assertThat(driver.getTitle()).isEqualTo("XHTML Test Page"); } /** @@ -428,11 +421,11 @@ public void testShouldTimeoutIfAPageTakesTooLongToLoadAfterClick() { } catch (RuntimeException e) { long end = System.currentTimeMillis(); - assertThat(e, is(instanceOf(TimeoutException.class))); + assertThat(e).isInstanceOf(TimeoutException.class); int duration = (int) (end - start); - assertThat(duration, greaterThan(2000)); - assertThat(duration, lessThan(5000)); + assertThat(duration).isGreaterThan(2000); + assertThat(duration).isLessThan(5000); } finally { driver.manage().timeouts().pageLoadTimeout(300, SECONDS); } @@ -460,11 +453,11 @@ public void testShouldTimeoutIfAPageTakesTooLongToRefresh() { } catch (RuntimeException e) { long end = System.currentTimeMillis(); - assertThat(e, is(instanceOf(TimeoutException.class))); + assertThat(e).isInstanceOf(TimeoutException.class); int duration = (int) (end - start); - assertThat(duration, greaterThan(2000)); - assertThat(duration, lessThan(4000)); + assertThat(duration).isGreaterThan(2000); + assertThat(duration).isLessThan(4000); } finally { driver.manage().timeouts().pageLoadTimeout(300, SECONDS); } @@ -525,11 +518,11 @@ private void assertPageLoadTimeoutIsEnforced(long webDriverPageLoadTimeout, } catch (RuntimeException e) { long end = System.currentTimeMillis(); - assertThat(e, is(instanceOf(TimeoutException.class))); + assertThat(e).isInstanceOf(TimeoutException.class); long duration = end - start; - assertThat(duration, greaterThan(webDriverPageLoadTimeout * 1000)); - assertThat(duration, lessThan((webDriverPageLoadTimeout + pageLoadTimeBuffer) * 1000)); + assertThat(duration).isGreaterThan(webDriverPageLoadTimeout * 1000); + assertThat(duration).isLessThan((webDriverPageLoadTimeout + pageLoadTimeBuffer) * 1000); } } } diff --git a/java/client/test/org/openqa/selenium/PlatformTest.java b/java/client/test/org/openqa/selenium/PlatformTest.java index 327de6ea08a79..b4e725b4fb115 100644 --- a/java/client/test/org/openqa/selenium/PlatformTest.java +++ b/java/client/test/org/openqa/selenium/PlatformTest.java @@ -17,76 +17,81 @@ package org.openqa.selenium; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; +import static org.openqa.selenium.Platform.ANDROID; +import static org.openqa.selenium.Platform.ANY; +import static org.openqa.selenium.Platform.LINUX; +import static org.openqa.selenium.Platform.MAC; +import static org.openqa.selenium.Platform.UNIX; +import static org.openqa.selenium.Platform.VISTA; +import static org.openqa.selenium.Platform.WIN8; +import static org.openqa.selenium.Platform.WIN8_1; +import static org.openqa.selenium.Platform.WINDOWS; +import static org.openqa.selenium.Platform.XP; import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; -@RunWith(JUnit4.class) public class PlatformTest { @Test public void testXpIsWindows() { - assertTrue(Platform.XP.is(Platform.WINDOWS)); + assertThat(XP.is(WINDOWS)).isTrue(); } @Test public void testVistaIsWindows() { - assertTrue(Platform.VISTA.is(Platform.WINDOWS)); + assertThat(VISTA.is(WINDOWS)).isTrue(); } @Test public void testWin8IsWindows() { - assertTrue(Platform.WIN8.is(Platform.WINDOWS)); + assertThat(WIN8.is(WINDOWS)).isTrue(); } @Test public void testWin81IsWindows() { - assertTrue(Platform.WIN8_1.is(Platform.WINDOWS)); + assertThat(WIN8_1.is(WINDOWS)).isTrue(); } @Test public void testLinuxIsUnix() { - assertTrue(Platform.LINUX.is(Platform.UNIX)); + assertThat(LINUX.is(UNIX)).isTrue(); } @Test public void testUnixIsNotLinux() { - assertFalse(Platform.UNIX.is(Platform.LINUX)); + assertThat(UNIX.is(LINUX)).isFalse(); } @Test public void androidIsAUnixVariant() { - assertTrue(Platform.ANDROID.is(Platform.UNIX)); + assertThat(ANDROID.is(UNIX)).isTrue(); } @Test public void testXpIsAny() { - assertTrue(Platform.XP.is(Platform.ANY)); + assertThat(XP.is(ANY)).isTrue(); } @Test public void testWindowsIsAny() { - assertTrue(Platform.WINDOWS.is(Platform.ANY)); + assertThat(WINDOWS.is(ANY)).isTrue(); } @Test public void testLinuxIsAny() { - assertTrue(Platform.LINUX.is(Platform.ANY)); + assertThat(LINUX.is(ANY)).isTrue(); } @Test public void windowsIsNotMacOS() { // Both of these are platform definitions, so return "null" for the family. - assertFalse(Platform.WINDOWS.is(Platform.MAC)); + assertThat(WINDOWS.is(MAC)).isFalse(); } @Test public void testUnixIsAny() { - assertTrue(Platform.UNIX.is(Platform.ANY)); + assertThat(UNIX.is(ANY)).isTrue(); } @Test @@ -116,51 +121,48 @@ public void testShouldIdentifyLinux() { @Test public void windowsIsWindows() { - assertTrue(Platform.WINDOWS.is(Platform.WINDOWS)); + assertThat(WINDOWS.is(WINDOWS)).isTrue(); } @Test public void macIsMac() { - assertTrue(Platform.MAC.is(Platform.MAC)); + assertThat(MAC.is(MAC)).isTrue(); } @Test public void linuxIsLinux() { - assertTrue(Platform.LINUX.is(Platform.LINUX)); + assertThat(LINUX.is(LINUX)).isTrue(); } @Test public void unixIsUnix() { - assertTrue(Platform.UNIX.is(Platform.UNIX)); + assertThat(UNIX.is(UNIX)).isTrue(); } @Test public void testWindows8Detection() { - assertEquals("Windows NT with os version 6.2 should be detected as Windows 8", - Platform.WIN8, Platform.extractFromSysProperty("windows nt (unknown)", "6.2")); + assertThat(Platform.extractFromSysProperty("windows nt (unknown)", "6.2")).isEqualTo(Platform.WIN8); } @Test public void testWindows81Detection() { - assertEquals("Windows NT with os version 6.3 should be detected as Windows 8.1", - Platform.WIN8_1, Platform.extractFromSysProperty("windows nt (unknown)", "6.3")); + assertThat(Platform.extractFromSysProperty("windows nt (unknown)", "6.3")).isEqualTo(Platform.WIN8_1); } @Test public void testWindowsIsWindows() { - assertEquals(Platform.fromString("windows"), Platform.WINDOWS); + assertThat(WINDOWS).isEqualTo(Platform.fromString("windows")); } @Test public void canParseMacOsXCorrectly() { - assertEquals(Platform.MAC, Platform.fromString("Mac OS X")); + assertThat(Platform.fromString("Mac OS X")).isEqualTo(MAC); } private void assertAllAre(Platform platform, String... osNames) { for (String osName : osNames) { Platform seen = Platform.extractFromSysProperty(osName); - assertTrue(String.format("Expected %s, but got %s from %s", platform, seen, osName), - seen.is(platform)); + assertThat(seen.is(platform)).isTrue(); } } diff --git a/java/client/test/org/openqa/selenium/PointTest.java b/java/client/test/org/openqa/selenium/PointTest.java index 31d3c8edee897..aee34979390da 100644 --- a/java/client/test/org/openqa/selenium/PointTest.java +++ b/java/client/test/org/openqa/selenium/PointTest.java @@ -17,24 +17,20 @@ package org.openqa.selenium; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotSame; +import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; /** * Tests WebDriver's Point class. */ -@RunWith(JUnit4.class) public class PointTest { @Test public void testSimpleAssignment() { Point p1 = new Point(30, 50); - assertEquals(30, p1.getX()); - assertEquals(50, p1.getY()); + assertThat(p1.getX()).isEqualTo(30); + assertThat(p1.getY()).isEqualTo(50); } @Test @@ -42,20 +38,20 @@ public void testEquality() { Point p1 = new Point(30, 60); Point p2 = new Point(40, 60); - assertNotSame(p1, p2); + assertThat(p1).isNotEqualTo(p2); // Doesn't have to be different, but known to be different for this case. - assertNotSame(p1.hashCode(), p2.hashCode()); + assertThat(p1.hashCode()).isNotEqualTo(p2.hashCode()); Point p1copy = new Point(30, 60); - assertEquals(p1, p1copy); - assertEquals(p1.hashCode(), p1copy.hashCode()); + assertThat(p1copy).isEqualTo(p1); + assertThat(p1copy.hashCode()).isEqualTo(p1.hashCode()); } @Test public void testMoveBy() { Point p1 = new Point(31, 42); - assertEquals(new Point(35, 47), p1.moveBy(4, 5)); + assertThat(p1.moveBy(4, 5)).isEqualTo(new Point(35, 47)); } } diff --git a/java/client/test/org/openqa/selenium/PositionAndSizeTest.java b/java/client/test/org/openqa/selenium/PositionAndSizeTest.java index b963755d5a511..af5599a05b0f5 100644 --- a/java/client/test/org/openqa/selenium/PositionAndSizeTest.java +++ b/java/client/test/org/openqa/selenium/PositionAndSizeTest.java @@ -17,13 +17,7 @@ package org.openqa.selenium; -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.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assume.assumeFalse; import static org.openqa.selenium.Platform.ANDROID; import static org.openqa.selenium.testing.Driver.CHROME; @@ -52,43 +46,43 @@ public void testShouldBeAbleToDetermineTheLocationOfAnElement() { WebElement element = driver.findElement(By.id("username")); Point location = element.getLocation(); - assertThat(location.getX() > 0, is(true)); - assertThat(location.getY() > 0, is(true)); + assertThat(location.getX()).isGreaterThan(0); + assertThat(location.getY()).isGreaterThan(0); } @Test public void testShouldGetCoordinatesOfAnElement() { driver.get(appServer.whereIs("coordinates_tests/simple_page.html")); - assertThat(getLocationInViewPort(By.id("box")), is(new Point(10, 10))); - assertThat(getLocationOnPage(By.id("box")), is(new Point(10, 10))); + assertThat(getLocationInViewPort(By.id("box"))).isEqualTo(new Point(10, 10)); + assertThat(getLocationOnPage(By.id("box"))).isEqualTo(new Point(10, 10)); } @Test public void testShouldGetCoordinatesOfAnEmptyElement() { driver.get(appServer.whereIs("coordinates_tests/page_with_empty_element.html")); - assertThat(getLocationInViewPort(By.id("box")), is(new Point(10, 10))); - assertThat(getLocationOnPage(By.id("box")), is(new Point(10, 10))); + assertThat(getLocationInViewPort(By.id("box"))).isEqualTo(new Point(10, 10)); + assertThat(getLocationOnPage(By.id("box"))).isEqualTo(new Point(10, 10)); } @Test public void testShouldGetCoordinatesOfATransparentElement() { driver.get(appServer.whereIs("coordinates_tests/page_with_transparent_element.html")); - assertThat(getLocationInViewPort(By.id("box")), is(new Point(10, 10))); - assertThat(getLocationOnPage(By.id("box")), is(new Point(10, 10))); + assertThat(getLocationInViewPort(By.id("box"))).isEqualTo(new Point(10, 10)); + assertThat(getLocationOnPage(By.id("box"))).isEqualTo(new Point(10, 10)); } @Test public void testShouldGetCoordinatesOfAHiddenElement() { driver.get(appServer.whereIs("coordinates_tests/page_with_hidden_element.html")); - assertThat(getLocationInViewPort(By.id("box")), is(new Point(10, 10))); - assertThat(getLocationOnPage(By.id("box")), is(new Point(10, 10))); + assertThat(getLocationInViewPort(By.id("box"))).isEqualTo(new Point(10, 10)); + assertThat(getLocationOnPage(By.id("box"))).isEqualTo(new Point(10, 10)); } @Test public void testShouldGetCoordinatesOfAnInvisibleElement() { driver.get(appServer.whereIs("coordinates_tests/page_with_invisible_element.html")); - assertThat(getLocationInViewPort(By.id("box")), is(new Point(0, 0))); - assertThat(getLocationOnPage(By.id("box")), is(new Point(0, 0))); + assertThat(getLocationInViewPort(By.id("box"))).isEqualTo(new Point(0, 0)); + assertThat(getLocationOnPage(By.id("box"))).isEqualTo(new Point(0, 0)); } @Test @@ -100,10 +94,10 @@ public void testShouldScrollPageAndGetCoordinatesOfAnElementThatIsOutOfViewPort( driver.get(appServer.whereIs("coordinates_tests/page_with_element_out_of_view.html")); int windowHeight = driver.manage().window().getSize().getHeight(); Point location = getLocationInViewPort(By.id("box")); - assertThat(location.getX(), is(10)); - assertThat(location.getY(), greaterThanOrEqualTo(0)); - assertThat(location.getY(), lessThanOrEqualTo(windowHeight - 100)); - assertThat(getLocationOnPage(By.id("box")), is(new Point(10, 5010))); + assertThat(location.getX()).isEqualTo(10); + assertThat(location.getY()).isGreaterThanOrEqualTo(0); + assertThat(location.getY()).isLessThanOrEqualTo(windowHeight - 100); + assertThat(getLocationOnPage(By.id("box"))).isEqualTo(new Point(10, 5010)); } @SwitchToTopAfterTest @@ -113,8 +107,8 @@ public void testShouldGetCoordinatesOfAnElementInAFrame() { driver.get(appServer.whereIs("coordinates_tests/element_in_frame.html")); driver.switchTo().frame("ifr"); WebElement box = driver.findElement(By.id("box")); - assertThat(box.getLocation(), is(new Point(10, 10))); - assertThat(getLocationOnPage(By.id("box")), is(new Point(10, 10))); + assertThat(box.getLocation()).isEqualTo(new Point(10, 10)); + assertThat(getLocationOnPage(By.id("box"))).isEqualTo(new Point(10, 10)); } @SwitchToTopAfterTest @@ -124,8 +118,8 @@ public void testShouldGetCoordinatesOfAnElementInAFrame() { public void testShouldGetCoordinatesInViewPortOfAnElementInAFrame() { driver.get(appServer.whereIs("coordinates_tests/element_in_frame.html")); driver.switchTo().frame("ifr"); - assertThat(getLocationInViewPort(By.id("box")), is(new Point(25, 25))); - assertThat(getLocationOnPage(By.id("box")), is(new Point(10, 10))); + assertThat(getLocationInViewPort(By.id("box"))).isEqualTo(new Point(25, 25)); + assertThat(getLocationOnPage(By.id("box"))).isEqualTo(new Point(10, 10)); } @SwitchToTopAfterTest @@ -136,8 +130,8 @@ public void testShouldGetCoordinatesInViewPortOfAnElementInANestedFrame() { driver.get(appServer.whereIs("coordinates_tests/element_in_nested_frame.html")); driver.switchTo().frame("ifr"); driver.switchTo().frame("ifr"); - assertThat(getLocationInViewPort(By.id("box")), is(new Point(40, 40))); - assertThat(getLocationOnPage(By.id("box")), is(new Point(10, 10))); + assertThat(getLocationInViewPort(By.id("box"))).isEqualTo(new Point(40, 40)); + assertThat(getLocationOnPage(By.id("box"))).isEqualTo(new Point(10, 10)); } @Test @@ -145,12 +139,12 @@ public void testShouldGetCoordinatesInViewPortOfAnElementInANestedFrame() { public void testShouldGetCoordinatesOfAnElementWithFixedPosition() { assumeFalse("Ignoring fixed-position elements in IE6", TestUtilities.isIe6(driver)); driver.get(appServer.whereIs("coordinates_tests/page_with_fixed_element.html")); - assertThat(getLocationInViewPort(By.id("fixed")).getY(), is(0)); - assertThat(getLocationOnPage(By.id("fixed")).getY(), is(0)); + assertThat(getLocationInViewPort(By.id("fixed")).getY()).isEqualTo(0); + assertThat(getLocationOnPage(By.id("fixed")).getY()).isEqualTo(0); driver.findElement(By.id("bottom")).click(); - assertThat(getLocationInViewPort(By.id("fixed")).getY(), is(0)); - assertThat(getLocationOnPage(By.id("fixed")).getY(), greaterThan(0)); + assertThat(getLocationInViewPort(By.id("fixed")).getY()).isEqualTo(0); + assertThat(getLocationOnPage(By.id("fixed")).getY()).isGreaterThan(0); } @Test @@ -159,8 +153,8 @@ public void testShouldCorrectlyIdentifyThatAnElementHasWidthAndHeight() { WebElement shrinko = driver.findElement(By.id("linkId")); Dimension size = shrinko.getSize(); - assertTrue("Width expected to be greater than 0", size.width > 0); - assertTrue("Height expected to be greater than 0", size.height > 0); + assertThat(size.width).isGreaterThan(0); + assertThat(size.height).isGreaterThan(0); } // TODO: This test's value seems dubious at best. The CSS spec does not define how browsers @@ -176,15 +170,15 @@ public void testShouldHandleNonIntegerPositionAndSize() { WebElement r2 = driver.findElement(By.id("r2")); String left = r2.getCssValue("left"); - assertTrue("left (\"" + left + "\") should start with \"10.9\".", left.startsWith("10.9")); + assertThat(left).startsWith("10.9"); String top = r2.getCssValue("top"); - assertTrue("top (\"" + top + "\") should start with \"10.1\".", top.startsWith("10.1")); - assertEquals(new Point(11, 10), r2.getLocation()); + assertThat(top).startsWith("10.1"); + assertThat(r2.getLocation()).isEqualTo(new Point(11, 10)); String width = r2.getCssValue("width"); - assertTrue("width (\"" + left + "\") should start with \"48.6\".", width.startsWith("48.6")); + assertThat(width).startsWith("48.6"); String height = r2.getCssValue("height"); - assertTrue("height (\"" + left + "\") should start with \"49.3\".", height.startsWith("49.3")); - assertEquals(r2.getSize(), new Dimension(49, 49)); + assertThat(height).startsWith("49.3"); + assertThat(r2.getSize()).isEqualTo(new Dimension(49, 49)); } private Point getLocationInViewPort(By locator) { diff --git a/java/client/test/org/openqa/selenium/ProxySettingTest.java b/java/client/test/org/openqa/selenium/ProxySettingTest.java index b909c64db7305..409f936aa0661 100644 --- a/java/client/test/org/openqa/selenium/ProxySettingTest.java +++ b/java/client/test/org/openqa/selenium/ProxySettingTest.java @@ -17,9 +17,7 @@ package org.openqa.selenium; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.openqa.selenium.remote.CapabilityType.PROXY; import static org.openqa.selenium.testing.Driver.SAFARI; @@ -84,7 +82,7 @@ public void canConfigureManualHttpProxy() { registerDriverTeardown(driver); driver.get(appServer.whereElseIs("simpleTest.html")); - assertTrue("Proxy should have been called", proxyServer.hasBeenCalled("simpleTest.html")); + assertThat(proxyServer.hasBeenCalled("simpleTest.html")).isTrue(); } @Test @@ -99,10 +97,10 @@ public void canConfigureNoProxy() { registerDriverTeardown(driver); driver.get(appServer.whereIs("simpleTest.html")); - assertFalse("Proxy should not have been called", proxyServer.hasBeenCalled("simpleTest.html")); + assertThat(proxyServer.hasBeenCalled("simpleTest.html")).isFalse(); driver.get(appServer.whereElseIs("simpleTest.html")); - assertTrue("Proxy should have been called", proxyServer.hasBeenCalled("simpleTest.html")); + assertThat(proxyServer.hasBeenCalled("simpleTest.html")).isTrue(); } @Test @@ -125,8 +123,7 @@ public void canConfigureProxyThroughPACFile() { registerDriverTeardown(driver); driver.get(appServer.whereElseIs("mouseOver.html")); - assertEquals("Should follow proxy to another server", - "Hello, world!", driver.findElement(By.tagName("h3")).getText()); + assertThat(driver.findElement(By.tagName("h3")).getText()).isEqualTo("Hello, world!"); } @Test @@ -154,12 +151,10 @@ public void canUsePACThatOnlyProxiesCertainHosts() { registerDriverTeardown(driver); driver.get("http://" + getHostAndPort(helloServer)); - assertEquals("Should follow proxy to another server", - "Goodbye, world!", driver.findElement(By.tagName("h3")).getText()); + assertThat(driver.findElement(By.tagName("h3")).getText()).isEqualTo("Goodbye, world!"); driver.get(appServer.whereElseIs("simpleTest.html")); - assertEquals("Proxy should have permitted direct access to host", - "Heading", driver.findElement(By.tagName("h1")).getText()); + assertThat(driver.findElement(By.tagName("h1")).getText()).isEqualTo("Heading"); } private void registerDriverTeardown(final WebDriver driver) { diff --git a/java/client/test/org/openqa/selenium/ProxyTest.java b/java/client/test/org/openqa/selenium/ProxyTest.java index 4b0e43d059067..51cb8436ce648 100644 --- a/java/client/test/org/openqa/selenium/ProxyTest.java +++ b/java/client/test/org/openqa/selenium/ProxyTest.java @@ -17,19 +17,18 @@ package org.openqa.selenium; -import static org.hamcrest.Matchers.instanceOf; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.openqa.selenium.Proxy.ProxyType.AUTODETECT; +import static org.openqa.selenium.Proxy.ProxyType.DIRECT; +import static org.openqa.selenium.Proxy.ProxyType.MANUAL; +import static org.openqa.selenium.Proxy.ProxyType.PAC; +import static org.openqa.selenium.Proxy.ProxyType.SYSTEM; +import static org.openqa.selenium.Proxy.ProxyType.UNSPECIFIED; import static org.openqa.selenium.remote.CapabilityType.PROXY; -import static org.openqa.selenium.testing.TestUtilities.catchThrowable; import org.junit.Ignore; import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; import org.openqa.selenium.Proxy.ProxyType; import org.openqa.selenium.json.Json; @@ -37,70 +36,69 @@ import java.util.HashMap; import java.util.Map; -@RunWith(JUnit4.class) public class ProxyTest { @Test public void testNotInitializedProxy() { Proxy proxy = new Proxy(); - assertEquals(ProxyType.UNSPECIFIED, proxy.getProxyType()); - - assertNull(proxy.getFtpProxy()); - assertNull(proxy.getHttpProxy()); - assertNull(proxy.getSslProxy()); - assertNull(proxy.getSocksProxy()); - assertNull(proxy.getSocksVersion()); - assertNull(proxy.getSocksUsername()); - assertNull(proxy.getSocksPassword()); - assertNull(proxy.getNoProxy()); - assertNull(proxy.getProxyAutoconfigUrl()); - assertFalse(proxy.isAutodetect()); + assertThat(proxy.getProxyType()).isEqualTo(UNSPECIFIED); + + assertThat(proxy.getFtpProxy()).isNull(); + assertThat(proxy.getHttpProxy()).isNull(); + assertThat(proxy.getSslProxy()).isNull(); + assertThat(proxy.getSocksProxy()).isNull(); + assertThat(proxy.getSocksVersion()).isNull(); + assertThat(proxy.getSocksUsername()).isNull(); + assertThat(proxy.getSocksPassword()).isNull(); + assertThat(proxy.getNoProxy()).isNull(); + assertThat(proxy.getProxyAutoconfigUrl()).isNull(); + assertThat(proxy.isAutodetect()).isFalse(); } @Test public void testCanNotChangeAlreadyInitializedProxyType() { final Proxy proxy = new Proxy(); - proxy.setProxyType(ProxyType.DIRECT); + proxy.setProxyType(DIRECT); - Throwable t = catchThrowable(() -> proxy.setAutodetect(true)); - assertThat(t, instanceOf(IllegalStateException.class)); + assertThatExceptionOfType(IllegalStateException.class) + .isThrownBy(() -> proxy.setAutodetect(true)); - Throwable t2 = catchThrowable(() -> proxy.setSocksPassword("")); - assertThat(t2, instanceOf(IllegalStateException.class)); + assertThatExceptionOfType(IllegalStateException.class) + .isThrownBy(() -> proxy.setSocksPassword("")); - Throwable t3 = catchThrowable(() -> proxy.setSocksUsername("")); - assertThat(t3, instanceOf(IllegalStateException.class)); + assertThatExceptionOfType(IllegalStateException.class) + .isThrownBy(() -> proxy.setSocksUsername("")); - Throwable t4 = catchThrowable(() -> proxy.setSocksProxy("")); - assertThat(t4, instanceOf(IllegalStateException.class)); + assertThatExceptionOfType(IllegalStateException.class) + .isThrownBy(() -> proxy.setSocksProxy("")); - Throwable t5 = catchThrowable(() -> proxy.setFtpProxy("")); - assertThat(t5, instanceOf(IllegalStateException.class)); + assertThatExceptionOfType(IllegalStateException.class) + .isThrownBy(() -> proxy.setFtpProxy("")); - Throwable t6 = catchThrowable(() -> proxy.setHttpProxy("")); - assertThat(t6, instanceOf(IllegalStateException.class)); + assertThatExceptionOfType(IllegalStateException.class) + .isThrownBy(() -> proxy.setHttpProxy("")); - Throwable t7 = catchThrowable(() -> proxy.setNoProxy("")); - assertThat(t7, instanceOf(IllegalStateException.class)); + assertThatExceptionOfType(IllegalStateException.class) + .isThrownBy(() -> proxy.setNoProxy("")); - Throwable t8 = catchThrowable(() -> proxy.setProxyAutoconfigUrl("")); - assertThat(t8, instanceOf(IllegalStateException.class)); + assertThatExceptionOfType(IllegalStateException.class) + .isThrownBy(() -> proxy.setProxyAutoconfigUrl("")); - Throwable t9 = catchThrowable(() -> proxy.setProxyType(ProxyType.SYSTEM)); - assertThat(t9, instanceOf(IllegalStateException.class)); + assertThatExceptionOfType(IllegalStateException.class) + .isThrownBy(() -> proxy.setProxyType(SYSTEM)); - Throwable t10 = catchThrowable(() -> proxy.setSslProxy("")); - assertThat(t10, instanceOf(IllegalStateException.class)); + assertThatExceptionOfType(IllegalStateException.class) + .isThrownBy(() -> proxy.setSslProxy("")); final Proxy proxy2 = new Proxy(); - proxy2.setProxyType(ProxyType.AUTODETECT); + proxy2.setProxyType(AUTODETECT); - Throwable t11 = catchThrowable(() -> proxy2.setProxyType(ProxyType.SYSTEM)); - assertThat(t11, instanceOf(IllegalStateException.class)); + assertThatExceptionOfType(IllegalStateException.class) + .isThrownBy(() -> proxy2.setProxyType(SYSTEM)); - Throwable t12 = catchThrowable(() -> proxy.setSocksVersion(5)); - assertThat(t12, instanceOf(IllegalStateException.class)); + assertThatExceptionOfType(IllegalStateException.class) + .isThrownBy(() -> proxy.setSocksVersion(5)); } @Test @@ -117,18 +115,18 @@ public void testManualProxy() { setSocksUsername("test1"). setSocksPassword("test2"); - assertEquals(ProxyType.MANUAL, proxy.getProxyType()); - assertEquals("ftp.proxy", proxy.getFtpProxy()); - assertEquals("http.proxy:1234", proxy.getHttpProxy()); - assertEquals("ssl.proxy", proxy.getSslProxy()); - assertEquals("socks.proxy:65555", proxy.getSocksProxy()); - assertEquals(Integer.valueOf(5), proxy.getSocksVersion()); - assertEquals("test1", proxy.getSocksUsername()); - assertEquals("test2", proxy.getSocksPassword()); - assertEquals("localhost,127.0.0.*", proxy.getNoProxy()); - - assertNull(proxy.getProxyAutoconfigUrl()); - assertFalse(proxy.isAutodetect()); + assertThat(proxy.getProxyType()).isEqualTo(MANUAL); + assertThat(proxy.getFtpProxy()).isEqualTo("ftp.proxy"); + assertThat(proxy.getHttpProxy()).isEqualTo("http.proxy:1234"); + assertThat(proxy.getSslProxy()).isEqualTo("ssl.proxy"); + assertThat(proxy.getSocksProxy()).isEqualTo("socks.proxy:65555"); + assertThat(proxy.getSocksVersion()).isEqualTo(Integer.valueOf(5)); + assertThat(proxy.getSocksUsername()).isEqualTo("test1"); + assertThat(proxy.getSocksPassword()).isEqualTo("test2"); + assertThat(proxy.getNoProxy()).isEqualTo("localhost,127.0.0.*"); + + assertThat(proxy.getProxyAutoconfigUrl()).isNull(); + assertThat(proxy.isAutodetect()).isFalse(); } @Test @@ -136,18 +134,18 @@ public void testPACProxy() { Proxy proxy = new Proxy(); proxy.setProxyAutoconfigUrl("http://aaa/bbb.pac"); - assertEquals(proxy.getProxyType(), ProxyType.PAC); - assertEquals("http://aaa/bbb.pac", proxy.getProxyAutoconfigUrl()); - - assertNull(proxy.getFtpProxy()); - assertNull(proxy.getHttpProxy()); - assertNull(proxy.getSslProxy()); - assertNull(proxy.getSocksProxy()); - assertNull(proxy.getSocksVersion()); - assertNull(proxy.getSocksUsername()); - assertNull(proxy.getSocksPassword()); - assertNull(proxy.getNoProxy()); - assertFalse(proxy.isAutodetect()); + assertThat(proxy.getProxyType()).isEqualTo(PAC); + assertThat(proxy.getProxyAutoconfigUrl()).isEqualTo("http://aaa/bbb.pac"); + + assertThat(proxy.getFtpProxy()).isNull(); + assertThat(proxy.getHttpProxy()).isNull(); + assertThat(proxy.getSslProxy()).isNull(); + assertThat(proxy.getSocksProxy()).isNull(); + assertThat(proxy.getSocksVersion()).isNull(); + assertThat(proxy.getSocksUsername()).isNull(); + assertThat(proxy.getSocksPassword()).isNull(); + assertThat(proxy.getNoProxy()).isNull(); + assertThat(proxy.isAutodetect()).isFalse(); } @Test @@ -155,18 +153,18 @@ public void testAutodetectProxy() { Proxy proxy = new Proxy(); proxy.setAutodetect(true); - assertEquals(proxy.getProxyType(), ProxyType.AUTODETECT); - assertTrue(proxy.isAutodetect()); - - assertNull(proxy.getFtpProxy()); - assertNull(proxy.getHttpProxy()); - assertNull(proxy.getSslProxy()); - assertNull(proxy.getSocksProxy()); - assertNull(proxy.getSocksVersion()); - assertNull(proxy.getSocksUsername()); - assertNull(proxy.getSocksPassword()); - assertNull(proxy.getNoProxy()); - assertNull(proxy.getProxyAutoconfigUrl()); + assertThat(proxy.getProxyType()).isEqualTo(AUTODETECT); + assertThat(proxy.isAutodetect()).isTrue(); + + assertThat(proxy.getFtpProxy()).isNull(); + assertThat(proxy.getHttpProxy()).isNull(); + assertThat(proxy.getSslProxy()).isNull(); + assertThat(proxy.getSocksProxy()).isNull(); + assertThat(proxy.getSocksVersion()).isNull(); + assertThat(proxy.getSocksUsername()).isNull(); + assertThat(proxy.getSocksPassword()).isNull(); + assertThat(proxy.getNoProxy()).isNull(); + assertThat(proxy.getProxyAutoconfigUrl()).isNull(); } @@ -185,18 +183,18 @@ public void manualProxyFromMap() { Proxy proxy = new Proxy(proxyData); - assertEquals(ProxyType.MANUAL, proxy.getProxyType()); - assertEquals("ftp.proxy", proxy.getFtpProxy()); - assertEquals("http.proxy:1234", proxy.getHttpProxy()); - assertEquals("ssl.proxy", proxy.getSslProxy()); - assertEquals("socks.proxy:65555", proxy.getSocksProxy()); - assertEquals(Integer.valueOf(5), proxy.getSocksVersion()); - assertEquals("test1", proxy.getSocksUsername()); - assertEquals("test2", proxy.getSocksPassword()); - assertEquals("localhost,127.0.0.*", proxy.getNoProxy()); - - assertNull(proxy.getProxyAutoconfigUrl()); - assertFalse(proxy.isAutodetect()); + assertThat(proxy.getProxyType()).isEqualTo(MANUAL); + assertThat(proxy.getFtpProxy()).isEqualTo("ftp.proxy"); + assertThat(proxy.getHttpProxy()).isEqualTo("http.proxy:1234"); + assertThat(proxy.getSslProxy()).isEqualTo("ssl.proxy"); + assertThat(proxy.getSocksProxy()).isEqualTo("socks.proxy:65555"); + assertThat(proxy.getSocksVersion()).isEqualTo(Integer.valueOf(5)); + assertThat(proxy.getSocksUsername()).isEqualTo("test1"); + assertThat(proxy.getSocksPassword()).isEqualTo("test2"); + assertThat(proxy.getNoProxy()).isEqualTo("localhost,127.0.0.*"); + + assertThat(proxy.getProxyAutoconfigUrl()).isNull(); + assertThat(proxy.isAutodetect()).isFalse(); } @Test @@ -214,16 +212,16 @@ public void manualProxyToJson() { Map json = proxy.toJson(); - assertEquals("MANUAL", json.get("proxyType")); - assertEquals("ftp.proxy", json.get("ftpProxy")); - assertEquals("http.proxy:1234", json.get("httpProxy")); - assertEquals("ssl.proxy", json.get("sslProxy")); - assertEquals("socks.proxy:65555", json.get("socksProxy")); - assertEquals(5, json.get("socksVersion")); - assertEquals("test1", json.get("socksUsername")); - assertEquals("test2", json.get("socksPassword")); - assertEquals(Arrays.asList("localhost", "127.0.0.*"), json.get("noProxy")); - assertEquals(9, json.entrySet().size()); + assertThat(json.get("proxyType")).isEqualTo("MANUAL"); + assertThat(json.get("ftpProxy")).isEqualTo("ftp.proxy"); + assertThat(json.get("httpProxy")).isEqualTo("http.proxy:1234"); + assertThat(json.get("sslProxy")).isEqualTo("ssl.proxy"); + assertThat(json.get("socksProxy")).isEqualTo("socks.proxy:65555"); + assertThat(json.get("socksVersion")).isEqualTo(5); + assertThat(json.get("socksUsername")).isEqualTo("test1"); + assertThat(json.get("socksPassword")).isEqualTo("test2"); + assertThat(json.get("noProxy")).isEqualTo(Arrays.asList("localhost", "127.0.0.*")); + assertThat(json.entrySet()).hasSize(9); } @Test @@ -234,18 +232,18 @@ public void pacProxyFromMap() { Proxy proxy = new Proxy(proxyData); - assertEquals(ProxyType.PAC, proxy.getProxyType()); - assertEquals("http://aaa/bbb.pac", proxy.getProxyAutoconfigUrl()); - - assertNull(proxy.getFtpProxy()); - assertNull(proxy.getHttpProxy()); - assertNull(proxy.getSslProxy()); - assertNull(proxy.getSocksProxy()); - assertNull(proxy.getSocksVersion()); - assertNull(proxy.getSocksUsername()); - assertNull(proxy.getSocksPassword()); - assertNull(proxy.getNoProxy()); - assertFalse(proxy.isAutodetect()); + assertThat(proxy.getProxyType()).isEqualTo(PAC); + assertThat(proxy.getProxyAutoconfigUrl()).isEqualTo("http://aaa/bbb.pac"); + + assertThat(proxy.getFtpProxy()).isNull(); + assertThat(proxy.getHttpProxy()).isNull(); + assertThat(proxy.getSslProxy()).isNull(); + assertThat(proxy.getSocksProxy()).isNull(); + assertThat(proxy.getSocksVersion()).isNull(); + assertThat(proxy.getSocksUsername()).isNull(); + assertThat(proxy.getSocksPassword()).isNull(); + assertThat(proxy.getNoProxy()).isNull(); + assertThat(proxy.isAutodetect()).isFalse(); } @Test @@ -256,9 +254,9 @@ public void pacProxyToJson() { Map json = proxy.toJson(); - assertEquals("PAC", json.get("proxyType")); - assertEquals("http://aaa/bbb.pac", json.get("proxyAutoconfigUrl")); - assertEquals(2, json.entrySet().size()); + assertThat(json.get("proxyType")).isEqualTo("PAC"); + assertThat(json.get("proxyAutoconfigUrl")).isEqualTo("http://aaa/bbb.pac"); + assertThat(json.entrySet()).hasSize(2); } @Test @@ -269,18 +267,18 @@ public void autodetectProxyFromMap() { Proxy proxy = new Proxy(proxyData); - assertEquals(ProxyType.AUTODETECT, proxy.getProxyType()); - assertTrue(proxy.isAutodetect()); - - assertNull(proxy.getFtpProxy()); - assertNull(proxy.getHttpProxy()); - assertNull(proxy.getSslProxy()); - assertNull(proxy.getSocksProxy()); - assertNull(proxy.getSocksVersion()); - assertNull(proxy.getSocksUsername()); - assertNull(proxy.getSocksPassword()); - assertNull(proxy.getNoProxy()); - assertNull(proxy.getProxyAutoconfigUrl()); + assertThat(proxy.getProxyType()).isEqualTo(AUTODETECT); + assertThat(proxy.isAutodetect()).isTrue(); + + assertThat(proxy.getFtpProxy()).isNull(); + assertThat(proxy.getHttpProxy()).isNull(); + assertThat(proxy.getSslProxy()).isNull(); + assertThat(proxy.getSocksProxy()).isNull(); + assertThat(proxy.getSocksVersion()).isNull(); + assertThat(proxy.getSocksUsername()).isNull(); + assertThat(proxy.getSocksPassword()).isNull(); + assertThat(proxy.getNoProxy()).isNull(); + assertThat(proxy.getProxyAutoconfigUrl()).isNull(); } @Test @@ -291,9 +289,9 @@ public void autodetectProxyToJson() { Map json = proxy.toJson(); - assertEquals("AUTODETECT", json.get("proxyType")); - assertTrue((Boolean) json.get("autodetect")); - assertEquals(2, json.entrySet().size()); + assertThat(json.get("proxyType")).isEqualTo("AUTODETECT"); + assertThat((Boolean) json.get("autodetect")).isTrue(); + assertThat(json.entrySet()).hasSize(2); } @Test @@ -303,18 +301,18 @@ public void systemProxyFromMap() { Proxy proxy = new Proxy(proxyData); - assertEquals(ProxyType.SYSTEM, proxy.getProxyType()); - - assertNull(proxy.getFtpProxy()); - assertNull(proxy.getHttpProxy()); - assertNull(proxy.getSslProxy()); - assertNull(proxy.getSocksProxy()); - assertNull(proxy.getSocksVersion()); - assertNull(proxy.getSocksUsername()); - assertNull(proxy.getSocksPassword()); - assertNull(proxy.getNoProxy()); - assertFalse(proxy.isAutodetect()); - assertNull(proxy.getProxyAutoconfigUrl()); + assertThat(proxy.getProxyType()).isEqualTo(SYSTEM); + + assertThat(proxy.getFtpProxy()).isNull(); + assertThat(proxy.getHttpProxy()).isNull(); + assertThat(proxy.getSslProxy()).isNull(); + assertThat(proxy.getSocksProxy()).isNull(); + assertThat(proxy.getSocksVersion()).isNull(); + assertThat(proxy.getSocksUsername()).isNull(); + assertThat(proxy.getSocksPassword()).isNull(); + assertThat(proxy.getNoProxy()).isNull(); + assertThat(proxy.isAutodetect()).isFalse(); + assertThat(proxy.getProxyAutoconfigUrl()).isNull(); } @Test @@ -324,8 +322,8 @@ public void systemProxyToJson() { Map json = proxy.toJson(); - assertEquals("SYSTEM", json.get("proxyType")); - assertEquals(1, json.entrySet().size()); + assertThat(json.get("proxyType")).isEqualTo("SYSTEM"); + assertThat(json.entrySet()).hasSize(1); } @Test @@ -335,18 +333,18 @@ public void directProxyFromMap() { Proxy proxy = new Proxy(proxyData); - assertEquals(ProxyType.DIRECT, proxy.getProxyType()); - - assertNull(proxy.getFtpProxy()); - assertNull(proxy.getHttpProxy()); - assertNull(proxy.getSslProxy()); - assertNull(proxy.getSocksProxy()); - assertNull(proxy.getSocksVersion()); - assertNull(proxy.getSocksUsername()); - assertNull(proxy.getSocksPassword()); - assertNull(proxy.getNoProxy()); - assertFalse(proxy.isAutodetect()); - assertNull(proxy.getProxyAutoconfigUrl()); + assertThat(proxy.getProxyType()).isEqualTo(DIRECT); + + assertThat(proxy.getFtpProxy()).isNull(); + assertThat(proxy.getHttpProxy()).isNull(); + assertThat(proxy.getSslProxy()).isNull(); + assertThat(proxy.getSocksProxy()).isNull(); + assertThat(proxy.getSocksVersion()).isNull(); + assertThat(proxy.getSocksUsername()).isNull(); + assertThat(proxy.getSocksPassword()).isNull(); + assertThat(proxy.getNoProxy()).isNull(); + assertThat(proxy.isAutodetect()).isFalse(); + assertThat(proxy.getProxyAutoconfigUrl()).isNull(); } @Test @@ -356,8 +354,8 @@ public void directProxyToJson() { Map json = proxy.toJson(); - assertEquals("DIRECT", json.get("proxyType")); - assertEquals(1, json.entrySet().size()); + assertThat(json.get("proxyType")).isEqualTo("DIRECT"); + assertThat(json.entrySet()).hasSize(1); } @Test @@ -370,9 +368,9 @@ public void constructingWithNullKeysWorksAsExpected() { Proxy proxy = Proxy.extractFrom(caps); - assertNull(proxy.getFtpProxy()); - assertFalse(proxy.isAutodetect()); - assertEquals("http://www.example.com", proxy.getHttpProxy()); + assertThat(proxy.getFtpProxy()).isNull(); + assertThat(proxy.isAutodetect()).isFalse(); + assertThat(proxy.getHttpProxy()).isEqualTo("http://www.example.com"); } @Test @@ -387,6 +385,6 @@ public void serialiazesAndDeserializesWithoutError() { Capabilities converted = new Json().toType(rawJson, Capabilities.class); Object returnedProxy = converted.getCapability(PROXY); - assertTrue(returnedProxy instanceof Proxy); + assertThat(returnedProxy).isInstanceOf(Proxy.class); } } diff --git a/java/client/test/org/openqa/selenium/ReferrerTest.java b/java/client/test/org/openqa/selenium/ReferrerTest.java index 7c9c9d53980f2..6b81c4b169655 100644 --- a/java/client/test/org/openqa/selenium/ReferrerTest.java +++ b/java/client/test/org/openqa/selenium/ReferrerTest.java @@ -18,7 +18,7 @@ package org.openqa.selenium; import static java.nio.charset.StandardCharsets.UTF_8; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import static org.openqa.selenium.remote.CapabilityType.PROXY; import static org.openqa.selenium.support.ui.ExpectedConditions.presenceOfElementLocated; import static org.openqa.selenium.support.ui.ExpectedConditions.titleIs; @@ -124,12 +124,10 @@ public void basicHistoryNavigationWithoutAProxy() { performNavigation(driver, page1Url); - assertEquals( - ImmutableList.of( - new HttpRequest(page1Url, null), - new HttpRequest(page2Url, page1Url), - new HttpRequest(page3Url, page2Url)), - testServer1.getRequests()); + assertThat(testServer1.getRequests()).isEqualTo(ImmutableList.of( + new HttpRequest(page1Url, null), + new HttpRequest(page2Url, page1Url), + new HttpRequest(page3Url, page2Url))); } /** @@ -148,17 +146,13 @@ public void crossDomainHistoryNavigationWithoutAProxy() { performNavigation(driver, page1Url); - assertEquals( - ImmutableList.of( - new HttpRequest(page1Url, null), - new HttpRequest(page3Url, page2Url)), - testServer1.getRequests()); - - assertEquals( - ImmutableList.of(new HttpRequest( - page2Url, - page1Url)), - testServer2.getRequests()); + assertThat(testServer1.getRequests()).isEqualTo(ImmutableList.of( + new HttpRequest(page1Url, null), + new HttpRequest(page3Url, page2Url))); + + assertThat(testServer2.getRequests()).isEqualTo(ImmutableList.of(new HttpRequest( + page2Url, + page1Url))); } /** @@ -181,12 +175,10 @@ public void basicHistoryNavigationWithADirectProxy() { performNavigation(driver, page1Url); - assertEquals( - ImmutableList.of( - new HttpRequest(page1Url, null), - new HttpRequest(page2Url, page1Url), - new HttpRequest(page3Url, page2Url)), - testServer1.getRequests()); + assertThat(testServer1.getRequests()).isEqualTo(ImmutableList.of( + new HttpRequest(page1Url, null), + new HttpRequest(page2Url, page1Url), + new HttpRequest(page3Url, page2Url))); } /** @@ -210,17 +202,13 @@ public void crossDomainHistoryNavigationWithADirectProxy() { performNavigation(driver, page1Url); - assertEquals( - ImmutableList.of( - new HttpRequest(page1Url, null), - new HttpRequest(page3Url, page2Url)), - testServer1.getRequests()); - - assertEquals( - ImmutableList.of(new HttpRequest( - page2Url, - page1Url)), - testServer2.getRequests()); + assertThat(testServer1.getRequests()).isEqualTo(ImmutableList.of( + new HttpRequest(page1Url, null), + new HttpRequest(page3Url, page2Url))); + + assertThat(testServer2.getRequests()).isEqualTo(ImmutableList.of(new HttpRequest( + page2Url, + page1Url))); } /** @@ -249,16 +237,12 @@ public void crossDomainHistoryNavigationWithAProxiedHost() { performNavigation(driver, page1Url); - assertEquals( - ImmutableList.of( - new HttpRequest(page1Url, null), - new HttpRequest(page3Url, page2Url)), - testServer1.getRequests()); + assertThat(testServer1.getRequests()).isEqualTo(ImmutableList.of( + new HttpRequest(page1Url, null), + new HttpRequest(page3Url, page2Url))); - assertEquals( - ImmutableList.of( - new HttpRequest(page2Url, page1Url)), - testServer2.getRequests()); + assertThat(testServer2.getRequests()).isEqualTo(ImmutableList.of( + new HttpRequest(page2Url, page1Url))); } /** @@ -286,16 +270,12 @@ public void crossDomainHistoryNavigationWhenProxyInterceptsHostRequests() { WebDriver driver = customDriverFactory.createDriver(proxyServer.getPacUrl()); performNavigation(driver, page1Url); - assertEquals( - ImmutableList.of( - new HttpRequest(page1Url, null), - new HttpRequest(page3Url, page2Url)), - testServer1.getRequests()); + assertThat(testServer1.getRequests()).isEqualTo(ImmutableList.of( + new HttpRequest(page1Url, null), + new HttpRequest(page3Url, page2Url))); - assertEquals( - ImmutableList.of( - new HttpRequest(page2Url, page1Url)), - proxyServer.getRequests()); + assertThat(proxyServer.getRequests()).isEqualTo(ImmutableList.of( + new HttpRequest(page2Url, page1Url))); } /** @@ -328,17 +308,13 @@ public void navigationWhenProxyInterceptsASpecificUrl() { WebDriver driver = customDriverFactory.createDriver(proxyServer.getPacUrl()); performNavigation(driver, page1Url); - assertEquals( - ImmutableList.of( - new HttpRequest(page1Url, null), - new HttpRequest(page3Url, page2Url)), - testServer1.getRequests()); - - assertEquals( - ImmutableList.of(new HttpRequest( - page2Url, - page1Url)), - proxyServer.getRequests()); + assertThat(testServer1.getRequests()).isEqualTo(ImmutableList.of( + new HttpRequest(page1Url, null), + new HttpRequest(page3Url, page2Url))); + + assertThat(proxyServer.getRequests()).isEqualTo(ImmutableList.of(new HttpRequest( + page2Url, + page1Url))); } private void performNavigation(WebDriver driver, String firstUrl) { diff --git a/java/client/test/org/openqa/selenium/RotatableTest.java b/java/client/test/org/openqa/selenium/RotatableTest.java index 14ad2e7b29285..0e1340c4300f2 100644 --- a/java/client/test/org/openqa/selenium/RotatableTest.java +++ b/java/client/test/org/openqa/selenium/RotatableTest.java @@ -17,9 +17,10 @@ package org.openqa.selenium; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assume.assumeTrue; +import static org.openqa.selenium.ScreenOrientation.LANDSCAPE; +import static org.openqa.selenium.ScreenOrientation.PORTRAIT; import org.junit.Before; import org.junit.Test; @@ -38,18 +39,18 @@ public void setUp() { @Test public void testRotateToLandscapeMode() { rotatable.rotate(ScreenOrientation.LANDSCAPE); - assertEquals(ScreenOrientation.LANDSCAPE, rotatable.getOrientation()); + assertThat(rotatable.getOrientation()).isEqualTo(LANDSCAPE); } @Test public void testRotateToPortrait() { rotatable.rotate(ScreenOrientation.PORTRAIT); - assertEquals(ScreenOrientation.PORTRAIT, rotatable.getOrientation()); + assertThat(rotatable.getOrientation()).isEqualTo(PORTRAIT); } @Test public void testGetOrientationReturnsInitialValue() { - assertNotNull(rotatable.getOrientation()); + assertThat(rotatable.getOrientation()).isNotNull(); } } diff --git a/java/client/test/org/openqa/selenium/SelectElementHandlingTest.java b/java/client/test/org/openqa/selenium/SelectElementHandlingTest.java index ffac87e900fba..58c656590e7a0 100644 --- a/java/client/test/org/openqa/selenium/SelectElementHandlingTest.java +++ b/java/client/test/org/openqa/selenium/SelectElementHandlingTest.java @@ -17,9 +17,7 @@ package org.openqa.selenium; -import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.openqa.selenium.testing.Driver.HTMLUNIT; import static org.openqa.selenium.testing.Driver.SAFARI; @@ -39,14 +37,14 @@ public void testShouldBePossibleToDeselectASingleOptionFromASelectWhichAllowsMul List options = multiSelect.findElements(By.tagName("option")); WebElement option = options.get(0); - assertThat(option.isSelected(), is(true)); + assertThat(option.isSelected()).isTrue(); option.click(); - assertThat(option.isSelected(), is(false)); + assertThat(option.isSelected()).isFalse(); option.click(); - assertThat(option.isSelected(), is(true)); + assertThat(option.isSelected()).isTrue(); option = options.get(2); - assertThat(option.isSelected(), is(true)); + assertThat(option.isSelected()).isTrue(); } @Test @@ -56,12 +54,12 @@ public void testShouldBeAbleToChangeTheSelectedOptionInASelect() { List options = selectBox.findElements(By.tagName("option")); WebElement one = options.get(0); WebElement two = options.get(1); - assertThat(one.isSelected(), is(true)); - assertThat(two.isSelected(), is(false)); + assertThat(one.isSelected()).isTrue(); + assertThat(two.isSelected()).isFalse(); two.click(); - assertThat(one.isSelected(), is(false)); - assertThat(two.isSelected(), is(true)); + assertThat(one.isSelected()).isFalse(); + assertThat(two.isSelected()).isTrue(); } @Test @@ -78,8 +76,7 @@ public void testShouldBeAbleToSelectMoreThanOneOptionFromASelectWhichAllowsMulti for (int i = 0; i < options.size(); i++) { WebElement option = options.get(i); - assertThat("Option at index is not selected but should be: " + i, option.isSelected(), - is(true)); + assertThat(option.isSelected()).as("Option at index %s", i).isTrue(); } } @@ -90,12 +87,12 @@ public void testShouldSelectFirstOptionByDefaultIfNoneIsSelected() { List options = selectBox.findElements(By.tagName("option")); WebElement one = options.get(0); WebElement two = options.get(1); - assertThat(one.isSelected(), is(true)); - assertThat(two.isSelected(), is(false)); + assertThat(one.isSelected()).isTrue(); + assertThat(two.isSelected()).isFalse(); two.click(); - assertThat(one.isSelected(), is(false)); - assertThat(two.isSelected(), is(true)); + assertThat(one.isSelected()).isFalse(); + assertThat(two.isSelected()).isTrue(); } @Test @@ -103,23 +100,23 @@ public void testCanSelectElementsInOptGroups() { driver.get(pages.selectPage); WebElement element = driver.findElement(By.id("two-in-group")); element.click(); - assertTrue("Expected to be selected", element.isSelected()); + assertThat(element.isSelected()).isTrue(); } @Test public void testCanGetValueFromOptionViaAttributeWhenAttributeDoesntExist() { driver.get(pages.formPage); WebElement element = driver.findElement(By.cssSelector("select[name='select-default'] option")); - assertThat(element.getAttribute("value"), is("One")); + assertThat(element.getAttribute("value")).isEqualTo("One"); element = driver.findElement(By.id("blankOption")); - assertThat(element.getAttribute("value"), is("")); + assertThat(element.getAttribute("value")).isEqualTo(""); } @Test public void testCanGetValueFromOptionViaAttributeWhenAttributeIsEmptyString() { driver.get(pages.formPage); WebElement element = driver.findElement(By.id("optionEmptyValueSet")); - assertThat(element.getAttribute("value"), is("")); + assertThat(element.getAttribute("value")).isEqualTo(""); } @Test @@ -127,7 +124,7 @@ public void testCanSelectFromMultipleSelectWhereValueIsBelowVisibleRange() { driver.get(pages.selectPage); WebElement option = driver.findElements(By.cssSelector("#selectWithMultipleLongList option")).get(4); option.click(); - assertThat(option.isSelected(), is(true)); + assertThat(option.isSelected()).isTrue(); } @Test @@ -135,7 +132,7 @@ public void testCannotSetDisabledOption() { driver.get(pages.selectPage); WebElement element = driver.findElement(By.cssSelector("#visibility .disabled")); element.click(); - assertTrue("Expected to not be selected", !element.isSelected()); + assertThat(element.isSelected()).isFalse(); } @Test @@ -144,7 +141,7 @@ public void testCanSetHiddenOption() { driver.get(pages.selectPage); WebElement element = driver.findElement(By.cssSelector("#visibility .hidden")); element.click(); - assertTrue("Expected to be selected", element.isSelected()); + assertThat(element.isSelected()).isTrue(); } @Test @@ -153,7 +150,7 @@ public void testCanSetInvisibleOption() { driver.get(pages.selectPage); WebElement element = driver.findElement(By.cssSelector("#visibility .invisible")); element.click(); - assertTrue("Expected to be selected", element.isSelected()); + assertThat(element.isSelected()).isTrue(); } @Test @@ -162,6 +159,6 @@ public void testCanHandleTransparentSelect() { driver.get(pages.selectPage); WebElement element = driver.findElement(By.cssSelector("#transparent option")); element.click(); - assertTrue("Expected to be selected", element.isSelected()); + assertThat(element.isSelected()).isTrue(); } } diff --git a/java/client/test/org/openqa/selenium/SessionHandlingTest.java b/java/client/test/org/openqa/selenium/SessionHandlingTest.java index b47e726b11a24..99807f816e3dc 100644 --- a/java/client/test/org/openqa/selenium/SessionHandlingTest.java +++ b/java/client/test/org/openqa/selenium/SessionHandlingTest.java @@ -17,12 +17,10 @@ package org.openqa.selenium; -import static org.hamcrest.Matchers.instanceOf; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.openqa.selenium.testing.Driver.FIREFOX; import static org.openqa.selenium.testing.Driver.MARIONETTE; import static org.openqa.selenium.testing.Driver.SAFARI; -import static org.openqa.selenium.testing.TestUtilities.catchThrowable; import org.junit.Test; import org.openqa.selenium.testing.Ignore; @@ -58,8 +56,7 @@ public void callingQuitAfterClosingTheLastWindowIsANoOp() { public void callingAnyOperationAfterClosingTheLastWindowShouldThrowAnException() { driver.close(); sleepTight(3000); - Throwable t = catchThrowable(driver::getCurrentUrl); - assertThat(t, instanceOf(NoSuchSessionException.class)); + assertThatExceptionOfType(NoSuchSessionException.class).isThrownBy(driver::getCurrentUrl); } @NoDriverAfterTest @@ -67,8 +64,7 @@ public void callingAnyOperationAfterClosingTheLastWindowShouldThrowAnException() public void callingAnyOperationAfterQuitShouldThrowAnException() { driver.quit(); sleepTight(3000); - Throwable t = catchThrowable(driver::getCurrentUrl); - assertThat(t, instanceOf(NoSuchSessionException.class)); + assertThatExceptionOfType(NoSuchSessionException.class).isThrownBy(driver::getCurrentUrl); } @NoDriverAfterTest diff --git a/java/client/test/org/openqa/selenium/SlowLoadingPageTest.java b/java/client/test/org/openqa/selenium/SlowLoadingPageTest.java index 3a63fddd08d3b..ea21f258a2802 100644 --- a/java/client/test/org/openqa/selenium/SlowLoadingPageTest.java +++ b/java/client/test/org/openqa/selenium/SlowLoadingPageTest.java @@ -17,7 +17,7 @@ package org.openqa.selenium; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; import org.openqa.selenium.testing.JUnit4TestBase; @@ -52,6 +52,6 @@ public void testRefreshShouldBlockUntilPageLoads() { } private static void assertElapsed(long expected, long actual) { - assertTrue(expected + "ms should have elapsed, but was: " + actual, expected <= actual); + assertThat(actual).isGreaterThanOrEqualTo(expected); } } diff --git a/java/client/test/org/openqa/selenium/StaleElementReferenceTest.java b/java/client/test/org/openqa/selenium/StaleElementReferenceTest.java index dc65a8b6d314b..d7ecdb36560d0 100644 --- a/java/client/test/org/openqa/selenium/StaleElementReferenceTest.java +++ b/java/client/test/org/openqa/selenium/StaleElementReferenceTest.java @@ -17,11 +17,9 @@ package org.openqa.selenium; -import static org.hamcrest.Matchers.instanceOf; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.openqa.selenium.support.ui.ExpectedConditions.stalenessOf; -import static org.openqa.selenium.testing.TestUtilities.catchThrowable; import org.junit.Test; import org.openqa.selenium.testing.JUnit4TestBase; @@ -33,8 +31,7 @@ public void testOldPage() { driver.get(pages.simpleTestPage); WebElement elem = driver.findElement(By.id("links")); driver.get(pages.xhtmlTestPage); - Throwable t = catchThrowable(elem::click); - assertThat(t, instanceOf(StaleElementReferenceException.class)); + assertThatExceptionOfType(StaleElementReferenceException.class).isThrownBy(elem::click); } @Test @@ -42,8 +39,7 @@ public void testShouldNotCrashWhenCallingGetSizeOnAnObsoleteElement() { driver.get(pages.simpleTestPage); WebElement elem = driver.findElement(By.id("links")); driver.get(pages.xhtmlTestPage); - Throwable t = catchThrowable(elem::getSize); - assertThat(t, instanceOf(StaleElementReferenceException.class)); + assertThatExceptionOfType(StaleElementReferenceException.class).isThrownBy(elem::getSize); } @Test @@ -51,8 +47,8 @@ public void testShouldNotCrashWhenQueryingTheAttributeOfAStaleElement() { driver.get(pages.xhtmlTestPage); WebElement heading = driver.findElement(By.xpath("//h1")); driver.get(pages.simpleTestPage); - Throwable t = catchThrowable(() -> heading.getAttribute("class")); - assertThat(t, instanceOf(StaleElementReferenceException.class)); + assertThatExceptionOfType(StaleElementReferenceException.class) + .isThrownBy(() -> heading.getAttribute("class")); } @Test @@ -60,11 +56,11 @@ public void testRemovingAnElementDynamicallyFromTheDomShouldCauseAStaleRefExcept driver.get(pages.javascriptPage); WebElement toBeDeleted = driver.findElement(By.id("deleted")); - assertTrue(toBeDeleted.isDisplayed()); + assertThat(toBeDeleted.isDisplayed()).isTrue(); driver.findElement(By.id("delete")).click(); boolean wasStale = wait.until(stalenessOf(toBeDeleted)); - assertTrue("Element should be stale at this point", wasStale); + assertThat(wasStale).isTrue(); } } diff --git a/java/client/test/org/openqa/selenium/SvgDocumentTest.java b/java/client/test/org/openqa/selenium/SvgDocumentTest.java index ccc54db44b663..683657ae32fd3 100644 --- a/java/client/test/org/openqa/selenium/SvgDocumentTest.java +++ b/java/client/test/org/openqa/selenium/SvgDocumentTest.java @@ -17,7 +17,7 @@ package org.openqa.selenium; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assume.assumeFalse; import static org.openqa.selenium.testing.Driver.CHROME; import static org.openqa.selenium.testing.Driver.HTMLUNIT; @@ -41,9 +41,9 @@ public void testClickOnSvgElement() { driver.get(pages.svgTestPage); WebElement rect = driver.findElement(By.id("rect")); - assertEquals("blue", rect.getAttribute("fill")); + assertThat(rect.getAttribute("fill")).isEqualTo("blue"); rect.click(); - assertEquals("green", rect.getAttribute("fill")); + assertThat(rect.getAttribute("fill")).isEqualTo("green"); } @Test @@ -54,9 +54,9 @@ public void testExecuteScriptInSvgDocument() { driver.get(pages.svgTestPage); WebElement rect = driver.findElement(By.id("rect")); - assertEquals("blue", rect.getAttribute("fill")); + assertThat(rect.getAttribute("fill")).isEqualTo("blue"); ((JavascriptExecutor) driver).executeScript("document.getElementById('rect').setAttribute('fill', 'yellow');"); - assertEquals("yellow", rect.getAttribute("fill")); + assertThat(rect.getAttribute("fill")).isEqualTo("yellow"); } } diff --git a/java/client/test/org/openqa/selenium/SvgElementTest.java b/java/client/test/org/openqa/selenium/SvgElementTest.java index 432695c968d9b..7c62a65929b2b 100644 --- a/java/client/test/org/openqa/selenium/SvgElementTest.java +++ b/java/client/test/org/openqa/selenium/SvgElementTest.java @@ -17,8 +17,7 @@ package org.openqa.selenium; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assume.assumeFalse; import static org.openqa.selenium.WaitingConditions.elementTextToEqual; import static org.openqa.selenium.testing.Driver.HTMLUNIT; @@ -46,19 +45,19 @@ public void testShouldClickOnGraphVisualElements() { WebElement svg = driver.findElement(By.cssSelector("svg")); List groupElements = svg.findElements(By.cssSelector("g")); - assertEquals(5, groupElements.size()); + assertThat(groupElements).hasSize(5); groupElements.get(1).click(); WebElement resultElement = driver.findElement(By.id("result")); wait.until(elementTextToEqual(resultElement, "slice_red")); - assertEquals("slice_red", resultElement.getText()); + assertThat(resultElement.getText()).isEqualTo("slice_red"); groupElements.get(2).click(); resultElement = driver.findElement(By.id("result")); wait.until(elementTextToEqual(resultElement, "slice_green")); - assertEquals("slice_green", resultElement.getText()); + assertThat(resultElement.getText()).isEqualTo("slice_green"); } private static WebElement findAppleElement(List textElements) { @@ -81,12 +80,12 @@ public void testShouldClickOnGraphTextElements() { List textElements = svg.findElements(By.cssSelector("text")); WebElement appleElement = findAppleElement(textElements); - assertNotNull(appleElement); + assertThat(appleElement).isNotNull(); appleElement.click(); WebElement resultElement = driver.findElement(By.id("result")); wait.until(elementTextToEqual(resultElement, "text_apple")); - assertEquals("text_apple", resultElement.getText()); + assertThat(resultElement.getText()).isEqualTo("text_apple"); } } diff --git a/java/client/test/org/openqa/selenium/TakesScreenshotTest.java b/java/client/test/org/openqa/selenium/TakesScreenshotTest.java index 14c40e8be1da1..ccc7f98654455 100644 --- a/java/client/test/org/openqa/selenium/TakesScreenshotTest.java +++ b/java/client/test/org/openqa/selenium/TakesScreenshotTest.java @@ -17,9 +17,7 @@ package org.openqa.selenium; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.fail; import static org.junit.Assume.assumeFalse; import static org.junit.Assume.assumeTrue; @@ -102,22 +100,22 @@ public void tearDown() { public void testGetScreenshotAsFile() { driver.get(pages.simpleTestPage); tempFile = screenshooter.getScreenshotAs(OutputType.FILE); - assertTrue(tempFile.exists()); - assertTrue(tempFile.length() > 0); + assertThat(tempFile.exists()).isTrue(); + assertThat(tempFile.length()).isGreaterThan(0); } @Test public void testGetScreenshotAsBase64() { driver.get(pages.simpleTestPage); String screenshot = screenshooter.getScreenshotAs(OutputType.BASE64); - assertTrue(screenshot.length() > 0); + assertThat(screenshot.length()).isGreaterThan(0); } @Test public void testGetScreenshotAsBinary() { driver.get(pages.simpleTestPage); byte[] screenshot = screenshooter.getScreenshotAs(OutputType.BYTES); - assertTrue(screenshot.length > 0); + assertThat(screenshot.length).isGreaterThan(0); } @Test @@ -151,17 +149,17 @@ public void testShouldCaptureScreenshotOfAnElement() throws Exception { WebElement element = driver.findElement(By.id("cell11")); byte[] imageData = element.getScreenshotAs(OutputType.BYTES); - assertTrue(imageData != null); - assertTrue(imageData.length > 0); + assertThat(imageData).isNotNull(); + assertThat(imageData.length).isGreaterThan(0); BufferedImage image = ImageIO.read(new ByteArrayInputStream(imageData)); - assertTrue(image != null); + assertThat(image).isNotNull(); Raster raster = image.getRaster(); String hex = String.format("#%02x%02x%02x", (raster.getSample(1, 1, 0)), (raster.getSample(1, 1, 1)), (raster.getSample(1, 1, 2))); - assertEquals("#0f12f7", hex); + assertThat(hex).isEqualTo("#0f12f7"); } @Test @@ -406,10 +404,10 @@ private BufferedImage getImage() { BufferedImage image = null; try { byte[] imageData = screenshooter.getScreenshotAs(OutputType.BYTES); - assertTrue(imageData != null); - assertTrue(imageData.length > 0); + assertThat(imageData).isNotNull(); + assertThat(imageData.length).isGreaterThan(0); image = ImageIO.read(new ByteArrayInputStream(imageData)); - assertTrue(image != null); + assertThat(image).isNotNull(); } catch (IOException e) { fail("Image screenshot file is invalid: " + e.getMessage()); } @@ -459,8 +457,8 @@ private Set scanActualColors(BufferedImage image, final int stepX, final try { int height = image.getHeight(); int width = image.getWidth(); - assertTrue(width > 0); - assertTrue(height > 0); + assertThat(width > 0).isTrue(); + assertThat(height > 0).isTrue(); Raster raster = image.getRaster(); for (int i = 0; i < width; i = i + stepX) { @@ -476,7 +474,7 @@ private Set scanActualColors(BufferedImage image, final int stepX, final fail("Unable to get actual colors from screenshot: " + e.getMessage()); } - assertTrue(colors.size() > 0); + assertThat(colors).isNotEmpty(); return colors; } @@ -488,8 +486,8 @@ private Set scanActualColors(BufferedImage image, final int stepX, final * @param actualColors - set of actual colors */ private void compareColors(Set expectedColors, Set actualColors) { - assertFalse("Actual image has only black color", onlyBlack(actualColors)); - assertFalse("Actual image has only white color", onlyWhite(actualColors)); + assertThat(onlyBlack(actualColors)).as("Only black").isFalse(); + assertThat(onlyWhite(actualColors)).as("Only white").isFalse(); // Ignore black and white for further comparison Set cleanActualColors = Sets.newHashSet(actualColors); diff --git a/java/client/test/org/openqa/selenium/TextHandlingTest.java b/java/client/test/org/openqa/selenium/TextHandlingTest.java index 2f2b4e1c2c891..4645930266cb9 100644 --- a/java/client/test/org/openqa/selenium/TextHandlingTest.java +++ b/java/client/test/org/openqa/selenium/TextHandlingTest.java @@ -17,17 +17,7 @@ package org.openqa.selenium; -import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.endsWith; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.not; -import static org.hamcrest.Matchers.startsWith; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotSame; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assume.assumeFalse; import static org.openqa.selenium.testing.Driver.ALL; import static org.openqa.selenium.testing.Driver.CHROME; @@ -36,9 +26,6 @@ import static org.openqa.selenium.testing.Driver.SAFARI; import static org.openqa.selenium.testing.TestUtilities.isChrome; -import org.hamcrest.Description; -import org.hamcrest.Matcher; -import org.hamcrest.TypeSafeMatcher; import org.junit.Test; import org.openqa.selenium.environment.webserver.Page; import org.openqa.selenium.testing.Ignore; @@ -46,8 +33,6 @@ import org.openqa.selenium.testing.NotYetImplemented; import org.openqa.selenium.testing.TestUtilities; -import java.util.regex.Pattern; - public class TextHandlingTest extends JUnit4TestBase { private final String newLine = "\n"; @@ -56,10 +41,10 @@ public class TextHandlingTest extends JUnit4TestBase { public void testShouldReturnTheTextContentOfASingleElementWithNoChildren() { driver.get(pages.simpleTestPage); String selectText = driver.findElement(By.id("oneline")).getText(); - assertThat(selectText, equalTo("A single line of text")); + assertThat(selectText).isEqualTo("A single line of text"); String getText = driver.findElement(By.id("oneline")).getText(); - assertThat(getText, equalTo("A single line of text")); + assertThat(getText).isEqualTo("A single line of text"); } @Test @@ -67,9 +52,10 @@ public void testShouldReturnTheEntireTextContentOfChildElements() { driver.get(pages.simpleTestPage); String text = driver.findElement(By.id("multiline")).getText(); - assertThat(text.contains("A div containing"), is(true)); - assertThat(text.contains("More than one line of text"), is(true)); - assertThat(text.contains("and block level elements"), is(true)); + assertThat(text).contains( + "A div containing", + "More than one line of text", + "and block level elements"); } @Test @@ -77,11 +63,9 @@ public void testShouldReturnTheEntireTextContentOfChildElements() { public void testShouldIgnoreScriptElements() { driver.get(pages.javascriptEnhancedForm); WebElement labelForUsername = driver.findElement(By.id("labelforusername")); - String text = labelForUsername.getText(); - assertThat(labelForUsername.findElements(By.tagName("script")).size(), is(1)); - assertThat(text, not(containsString("document.getElementById"))); - assertThat(text, is("Username:")); + assertThat(labelForUsername.findElements(By.tagName("script"))).hasSize(1); + assertThat(labelForUsername.getText()).isEqualTo("Username:"); } @Test @@ -90,9 +74,10 @@ public void testShouldRepresentABlockLevelElementAsANewline() { driver.get(pages.simpleTestPage); String text = driver.findElement(By.id("multiline")).getText(); - assertThat(text, startsWith("A div containing" + newLine)); - assertThat(text, containsString("More than one line of text" + newLine)); - assertThat(text, endsWith("and block level elements")); + assertThat(text) + .startsWith("A div containing" + newLine) + .contains("More than one line of text" + newLine) + .endsWith("and block level elements"); } @Test @@ -101,7 +86,7 @@ public void testShouldCollapseMultipleWhitespaceCharactersIntoASingleSpace() { driver.get(pages.simpleTestPage); String text = driver.findElement(By.id("lotsofspaces")).getText(); - assertThat(text, equalTo("This line has lots of spaces.")); + assertThat(text).isEqualTo("This line has lots of spaces."); } @Test @@ -110,8 +95,7 @@ public void testShouldTrimText() { driver.get(pages.simpleTestPage); String text = driver.findElement(By.id("multiline")).getText(); - assertThat(text, startsWith("A div containing")); - assertThat(text, endsWith("block level elements")); + assertThat(text).startsWith("A div containing").endsWith("block level elements"); } @Test @@ -120,44 +104,43 @@ public void testShouldConvertANonBreakingSpaceIntoANormalSpaceCharacter() { driver.get(pages.simpleTestPage); String text = driver.findElement(By.id("nbsp")).getText(); - assertThat(text, equalTo("This line has a non-breaking space")); + assertThat(text).isEqualTo("This line has a non-breaking space"); } @Test @NotYetImplemented(value = SAFARI, reason = "getText does not normalize spaces") public void testShouldNotCollapseANonBreakingSpaces() { driver.get(pages.simpleTestPage); - WebElement element = driver.findElement(By.id("nbspandspaces")); - String text = element.getText(); + String text = driver.findElement(By.id("nbspandspaces")).getText(); - assertThat(text, equalTo("This line has a non-breaking space and spaces")); + assertThat(text).isEqualTo("This line has a non-breaking space and spaces"); } @Test @NotYetImplemented(value = SAFARI, reason = "getText does not normalize spaces") public void testShouldNotTrimNonBreakingSpacesAtTheEndOfALineInTheMiddleOfText() { driver.get(pages.simpleTestPage); - WebElement element = driver.findElement(By.id("multilinenbsp")); - String text = element.getText(); - assertThat(text, startsWith("These lines \n")); + String text = driver.findElement(By.id("multilinenbsp")).getText(); + + assertThat(text).startsWith("These lines \n"); } @Test @NotYetImplemented(value = SAFARI, reason = "getText does not normalize spaces") public void testShouldNotTrimNonBreakingSpacesAtTheStartOfALineInTheMiddleOfText() { driver.get(pages.simpleTestPage); - WebElement element = driver.findElement(By.id("multilinenbsp")); - String text = element.getText(); - assertThat(text, containsString("\n have")); + String text = driver.findElement(By.id("multilinenbsp")).getText(); + + assertThat(text).contains("\n have"); } @Test @NotYetImplemented(value = SAFARI, reason = "getText does not normalize spaces") public void testShouldNotTrimTrailingNonBreakingSpacesInMultilineText() { driver.get(pages.simpleTestPage); - WebElement element = driver.findElement(By.id("multilinenbsp")); - String text = element.getText(); - assertThat(text, endsWith("trailing NBSPs ")); + String text = driver.findElement(By.id("multilinenbsp")).getText(); + + assertThat(text).endsWith("trailing NBSPs "); } @Test @@ -166,8 +149,8 @@ public void testHavingInlineElementsShouldNotAffectHowTextIsReturned() { driver.get(pages.simpleTestPage); String text = driver.findElement(By.id("inline")).getText(); - assertThat(text, - equalTo("This line has text within elements that are meant to be displayed inline")); + assertThat(text) + .isEqualTo("This line has text within elements that are meant to be displayed inline"); } @Test @@ -175,7 +158,7 @@ public void testShouldReturnTheEntireTextOfInlineElements() { driver.get(pages.simpleTestPage); String text = driver.findElement(By.id("span")).getText(); - assertThat(text, equalTo("An inline element")); + assertThat(text).isEqualTo("An inline element"); } @Test @@ -183,10 +166,10 @@ public void testShouldRetainTheFormattingOfTextWithinAPreElement() { driver.get(pages.simpleTestPage); String text = driver.findElement(By.id("preformatted")).getText(); - assertThat(text, equalTo(" This section has a preformatted\n" + - " text block \n" + - " split in four lines\n" + - " ")); + assertThat(text).isEqualTo(" This section has a preformatted\n" + + " text block \n" + + " split in four lines\n" + + " "); } @Test @@ -194,12 +177,13 @@ public void testShouldRetainTheFormattingOfTextWithinAPreElement() { public void testShouldRetainTheFormatingOfTextWithinAPreElementThatIsWithinARegularBlock() { driver.get(pages.simpleTestPage); String text = driver.findElement(By.id("div-with-pre")).getText(); - assertThat(text, equalTo("before pre\n" + - " This section has a preformatted\n" + - " text block \n" + - " split in four lines\n" + - " \n" + - "after pre")); + + assertThat(text).isEqualTo("before pre\n" + + " This section has a preformatted\n" + + " text block \n" + + " split in four lines\n" + + " \n" + + "after pre"); } @Test @@ -216,7 +200,7 @@ public void testShouldBeAbleToSetMoreThanOneLineOfTextInATextArea() { textarea.sendKeys(expectedText); String seenText = textarea.getAttribute("value"); - assertThat(seenText, equalTo(expectedText)); + assertThat(seenText).isEqualTo(expectedText); } @Test @@ -227,24 +211,24 @@ public void testShouldBeAbleToEnterDatesAfterFillingInOtherValuesFirst() { input.sendKeys(expectedValue); String seenValue = input.getAttribute("value"); - assertThat(seenValue, equalTo(expectedValue)); + assertThat(seenValue).isEqualTo(expectedValue); } @Test @NotYetImplemented(value = SAFARI, reason = "getText does not normalize spaces") public void testShouldReturnEmptyStringWhenTextIsOnlySpaces() { driver.get(pages.xhtmlTestPage); - String text = driver.findElement(By.id("spaces")).getText(); - assertThat(text, equalTo("")); + + assertThat(text).isEqualTo(""); } @Test public void testShouldReturnEmptyStringWhenTextIsEmpty() { driver.get(pages.xhtmlTestPage); - String text = driver.findElement(By.id("empty")).getText(); - assertThat(text, equalTo("")); + + assertThat(text).isEqualTo(""); } @Test @@ -252,48 +236,46 @@ public void testShouldReturnEmptyStringWhenTagIsSelfClosing() { assumeFalse("IE version < 9 doesn't support application/xhtml+xml mime type", TestUtilities.isOldIe(driver)); driver.get(pages.xhtmlFormPage); - String text = driver.findElement(By.id("self-closed")).getText(); - assertThat(text, equalTo("")); + + assertThat(text).isEqualTo(""); } @Test public void testShouldNotTrimSpacesWhenLineWraps() { driver.get(pages.simpleTestPage); - String text = driver.findElement(By.xpath("//table/tbody/tr[1]/td[1]")).getText(); - assertThat(text, equalTo("beforeSpace afterSpace")); + + assertThat(text).isEqualTo("beforeSpace afterSpace"); } @Test @NotYetImplemented(value = SAFARI, reason = "getText does not normalize spaces") public void testShouldHandleSiblingBlockLevelElements() { driver.get(pages.simpleTestPage); - String text = driver.findElement(By.id("twoblocks")).getText(); - assertThat(text, is("Some text" + newLine + "Some more text")); + assertThat(text).isEqualTo("Some text" + newLine + "Some more text"); } @Test @NotYetImplemented(value = SAFARI, reason = "getText does not normalize spaces") public void testShouldHandleNestedBlockLevelElements() { driver.get(pages.simpleTestPage); - String text = driver.findElement(By.id("nestedblocks")).getText(); - assertThat(text, is("Cheese" + newLine + "Some text" + newLine + "Some more text" + newLine - + "and also" + newLine + "Brie")); + assertThat(text) + .isEqualTo("Cheese" + newLine + "Some text" + newLine + "Some more text" + newLine + + "and also" + newLine + "Brie"); } @Test @NotYetImplemented(value = SAFARI, reason = "getText does not normalize spaces") public void testShouldHandleWhitespaceInInlineElements() { driver.get(pages.simpleTestPage); - String text = driver.findElement(By.id("inlinespan")).getText(); - assertThat(text, is("line has text")); + assertThat(text).isEqualTo("line has text"); } @Test @@ -301,7 +283,7 @@ public void testReadALargeAmountOfData() { driver.get(pages.macbethPage); String source = driver.getPageSource().trim().toLowerCase(); - assertThat(source.endsWith(""), is(true)); + assertThat(source).endsWith(""); } @Test @@ -312,22 +294,7 @@ public void testGetTextWithLineBreakForInlineElement() { WebElement label = driver.findElement(By.id("label1")); String labelText = label.getText(); - assertThat(labelText, matchesPattern("foo[\\n\\r]+bar")); - } - - private Matcher matchesPattern(String javaRegex) { - final Pattern pattern = Pattern.compile(javaRegex); - - return new TypeSafeMatcher() { - @Override - public boolean matchesSafely(String s) { - return pattern.matcher(s).matches(); - } - - public void describeTo(Description description) { - description.appendText("a string matching the pattern " + pattern); - } - }; + assertThat(labelText).matches("foo[\\n\\r]+bar"); } @Test @@ -338,8 +305,8 @@ public void testShouldOnlyIncludeVisibleText() { String empty = driver.findElement(By.id("suppressedParagraph")).getText(); String explicit = driver.findElement(By.id("outer")).getText(); - assertEquals("", empty); - assertEquals("sub-element that is explicitly visible", explicit); + assertThat(empty).isEqualTo(""); + assertThat(explicit).isEqualTo("sub-element that is explicitly visible"); } @Test @@ -350,22 +317,23 @@ public void testShouldGetTextFromTableCells() { WebElement tr = driver.findElement(By.id("hidden_text")); String text = tr.getText(); - assertTrue(text.contains("some text")); - assertFalse(text.contains("some more text")); + assertThat(text).contains("some text", "some more text"); } @Test public void testTextOfAnInputFieldShouldBeEmpty() { driver.get(pages.formPage); - WebElement input = driver.findElement(By.id("inputWithText")); - assertEquals("", input.getText()); + String text = driver.findElement(By.id("inputWithText")).getText(); + + assertThat(text).isEqualTo(""); } @Test public void testTextOfATextAreaShouldBeEqualToItsDefaultText() { driver.get(pages.formPage); - WebElement area = driver.findElement(By.id("withText")); - assertEquals("Example text", area.getText()); + String text = driver.findElement(By.id("withText")).getText(); + + assertThat(text).isEqualTo("Example text"); } @Test @@ -375,7 +343,8 @@ public void testTextOfATextAreaShouldBeEqualToItsDefaultTextEvenAfterTyping() { WebElement area = driver.findElement(By.id("withText")); String oldText = area.getText(); area.sendKeys("New Text"); - assertEquals(oldText, area.getText()); + + assertThat(area.getText()).isEqualTo(oldText); } @Test @@ -385,22 +354,21 @@ public void testTextOfATextAreaShouldBeEqualToItsDefaultTextEvenAfterChangingThe WebElement area = driver.findElement(By.id("withText")); String oldText = area.getAttribute("value"); ((JavascriptExecutor) driver).executeScript("arguments[0].value = arguments[1]", area, "New Text"); - assertEquals(oldText, area.getText()); + assertThat(area.getText()).isEqualTo(oldText); } @Test public void testShouldGetTextWhichIsAValidJSONObject() { driver.get(pages.simpleTestPage); WebElement element = driver.findElement(By.id("simpleJsonText")); - assertEquals("{a=\"b\", c=1, d=true}", element.getText()); - // assertEquals("{a=\"b\", \"c\"=d, e=true, f=\\123\\\\g\\\\\"\"\"\\\'}", element.getText()); + assertThat(element.getText()).isEqualTo("{a=\"b\", c=1, d=true}"); } @Test public void testShouldGetTextWhichIsAValidComplexJSONObject() { driver.get(pages.simpleTestPage); WebElement element = driver.findElement(By.id("complexJsonText")); - assertEquals("{a=\"\\\\b\\\\\\\"\'\\\'\"}", element.getText()); + assertThat(element.getText()).isEqualTo("{a=\"\\\\b\\\\\\\"\'\\\'\"}"); } @Test @@ -411,11 +379,11 @@ public void testShouldNotReturnLtrMarks() { WebElement element = driver.findElement(By.id("EH")).findElement(By.tagName("nobr")); String text = element.getText(); String expected = "Some notes"; - assertNotSame("RTL mark should not be present", text.codePointAt(0), 8206); + assertThat(text.codePointAt(0)).describedAs("RTL mark should not be present").isNotEqualTo(8206); // Note: If this assertion fails but the content of the strings *looks* the same // it may be because of hidden unicode LTR character being included in the string. // That's the reason for the previous assert. - assertEquals(expected, element.getText()); + assertThat(element.getText()).isEqualTo(expected); } @Test @@ -424,7 +392,7 @@ public void testShouldTrimTextWithMultiByteWhitespaces() { driver.get(pages.simpleTestPage); String text = driver.findElement(By.id("trimmedSpace")).getText(); - assertEquals("test", text); + assertThat(text).isEqualTo("test"); } @Test @@ -434,9 +402,9 @@ public void canHandleTextThatLooksLikeANumber() { "
12,345
", "
12 345
"))); - assertThat(driver.findElement(By.id("point")).getText(), is("12.345")); - assertThat(driver.findElement(By.id("comma")).getText(), is("12,345")); - assertThat(driver.findElement(By.id("space")).getText(), is("12 345")); + assertThat(driver.findElement(By.id("point")).getText()).isEqualTo("12.345"); + assertThat(driver.findElement(By.id("comma")).getText()).isEqualTo("12,345"); + assertThat(driver.findElement(By.id("space")).getText()).isEqualTo("12 345"); } @Test @@ -445,10 +413,12 @@ public void canHandleTextThatLooksLikeANumber() { @NotYetImplemented(value = SAFARI, reason = "getText does not normalize spaces") public void canHandleTextTransformProperty() { driver.get(pages.simpleTestPage); - assertThat(driver.findElement(By.id("capitalized")).getText(), is( - isChrome(driver) ? "Hello, World! Bla-Bla-BLA" : "Hello, World! Bla-bla-BLA")); - assertThat(driver.findElement(By.id("lowercased")).getText(), is("hello, world! bla-bla-bla")); - assertThat(driver.findElement(By.id("uppercased")).getText(), is("HELLO, WORLD! BLA-BLA-BLA")); + assertThat(driver.findElement(By.id("capitalized")).getText()) + .isEqualTo(isChrome(driver) ? "Hello, World! Bla-Bla-BLA" : "Hello, World! Bla-bla-BLA"); + assertThat(driver.findElement(By.id("lowercased")).getText()) + .isEqualTo("hello, world! bla-bla-bla"); + assertThat(driver.findElement(By.id("uppercased")).getText()) + .isEqualTo("HELLO, WORLD! BLA-BLA-BLA"); } } diff --git a/java/client/test/org/openqa/selenium/TextPagesTest.java b/java/client/test/org/openqa/selenium/TextPagesTest.java index 59cb3d268888d..abb5422a3aa47 100644 --- a/java/client/test/org/openqa/selenium/TextPagesTest.java +++ b/java/client/test/org/openqa/selenium/TextPagesTest.java @@ -17,14 +17,12 @@ package org.openqa.selenium; -import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.instanceOf; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.openqa.selenium.testing.Driver.CHROME; import static org.openqa.selenium.testing.Driver.IE; import static org.openqa.selenium.testing.Driver.MARIONETTE; import static org.openqa.selenium.testing.Driver.SAFARI; -import static org.openqa.selenium.testing.TestUtilities.catchThrowable; import org.junit.Before; import org.junit.Test; @@ -45,7 +43,7 @@ public void setUp() { public void testShouldBeAbleToLoadASimplePageOfText() { driver.get(textPage); String source = driver.getPageSource(); - assertThat(source, containsString("Test")); + assertThat(source).contains("Test"); } @Test @@ -57,7 +55,7 @@ public void testShouldThrowExceptionWhenAddingCookieToAPageThatIsNotHtml() { driver.get(textPage); Cookie cookie = new Cookie.Builder("hello", "goodbye").build(); - Throwable t = catchThrowable(() -> driver.manage().addCookie(cookie)); - assertThat(t, instanceOf(WebDriverException.class)); + assertThatExceptionOfType(WebDriverException.class) + .isThrownBy(() -> driver.manage().addCookie(cookie)); } } diff --git a/java/client/test/org/openqa/selenium/TypingTest.java b/java/client/test/org/openqa/selenium/TypingTest.java index 7937e95d1bafd..7489ecde32924 100644 --- a/java/client/test/org/openqa/selenium/TypingTest.java +++ b/java/client/test/org/openqa/selenium/TypingTest.java @@ -17,25 +17,18 @@ package org.openqa.selenium; -import static org.hamcrest.Matchers.anyOf; -import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.instanceOf; -import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static com.google.common.base.Joiner.on; import static org.junit.Assume.assumeFalse; import static org.openqa.selenium.WaitingConditions.elementValueToEqual; import static org.openqa.selenium.testing.Driver.IE; import static org.openqa.selenium.testing.Driver.MARIONETTE; import static org.openqa.selenium.testing.Driver.SAFARI; -import static org.openqa.selenium.testing.TestUtilities.catchThrowable; import static org.openqa.selenium.testing.TestUtilities.getEffectivePlatform; import static org.openqa.selenium.testing.TestUtilities.getFirefoxVersion; import static org.openqa.selenium.testing.TestUtilities.isFirefox; -import com.google.common.base.Joiner; - import org.junit.Test; import org.openqa.selenium.testing.Ignore; import org.openqa.selenium.testing.JUnit4TestBase; @@ -52,7 +45,7 @@ public void testShouldFireKeyPressEvents() { keyReporter.sendKeys("a"); WebElement result = driver.findElement(By.id("result")); - assertThat(result.getText(), containsString("press:")); + assertThat(result.getText()).contains("press:"); } @Test @@ -63,7 +56,7 @@ public void testShouldFireKeyDownEvents() { keyReporter.sendKeys("I"); WebElement result = driver.findElement(By.id("result")); - assertThat(result.getText(), containsString("down:")); + assertThat(result.getText()).contains("down:"); } @Test @@ -74,7 +67,7 @@ public void testShouldFireKeyUpEvents() { keyReporter.sendKeys("a"); WebElement result = driver.findElement(By.id("result")); - assertThat(result.getText(), containsString("up:")); + assertThat(result.getText()).contains("up:"); } @Test @@ -84,7 +77,7 @@ public void testShouldTypeLowerCaseLetters() { WebElement keyReporter = driver.findElement(By.id("keyReporter")); keyReporter.sendKeys("abc def"); - assertThat(keyReporter.getAttribute("value"), is("abc def")); + assertThat(keyReporter.getAttribute("value")).isEqualTo("abc def"); } @Test @@ -94,7 +87,7 @@ public void testShouldBeAbleToTypeCapitalLetters() { WebElement keyReporter = driver.findElement(By.id("keyReporter")); keyReporter.sendKeys("ABC DEF"); - assertThat(keyReporter.getAttribute("value"), is("ABC DEF")); + assertThat(keyReporter.getAttribute("value")).isEqualTo("ABC DEF"); } @Test @@ -104,7 +97,7 @@ public void testShouldBeAbleToTypeQuoteMarks() { WebElement keyReporter = driver.findElement(By.id("keyReporter")); keyReporter.sendKeys("\""); - assertThat(keyReporter.getAttribute("value"), is("\"")); + assertThat(keyReporter.getAttribute("value")).isEqualTo("\""); } @Test @@ -120,7 +113,7 @@ public void testShouldBeAbleToTypeTheAtCharacter() { WebElement keyReporter = driver.findElement(By.id("keyReporter")); keyReporter.sendKeys("@"); - assertThat(keyReporter.getAttribute("value"), is("@")); + assertThat(keyReporter.getAttribute("value")).isEqualTo("@"); } @Test @@ -130,7 +123,7 @@ public void testShouldBeAbleToMixUpperAndLowerCaseLetters() { WebElement keyReporter = driver.findElement(By.id("keyReporter")); keyReporter.sendKeys("me@eXample.com"); - assertThat(keyReporter.getAttribute("value"), is("me@eXample.com")); + assertThat(keyReporter.getAttribute("value")).isEqualTo("me@eXample.com"); } @Test @@ -140,7 +133,7 @@ public void testArrowKeysShouldNotBePrintable() { WebElement keyReporter = driver.findElement(By.id("keyReporter")); keyReporter.sendKeys(Keys.ARROW_LEFT); - assertThat(keyReporter.getAttribute("value"), is("")); + assertThat(keyReporter.getAttribute("value")).isEqualTo(""); } @Test @@ -150,7 +143,7 @@ public void testShouldBeAbleToUseArrowKeys() { WebElement keyReporter = driver.findElement(By.id("keyReporter")); keyReporter.sendKeys("tet", Keys.ARROW_LEFT, "s"); - assertThat(keyReporter.getAttribute("value"), is("test")); + assertThat(keyReporter.getAttribute("value")).isEqualTo("test"); } @Test @@ -162,7 +155,7 @@ public void testWillSimulateAKeyUpWhenEnteringTextIntoInputElements() { element.sendKeys("I like cheese"); WebElement result = driver.findElement(By.id("result")); - assertThat(result.getText(), equalTo("I like cheese")); + assertThat(result.getText()).isEqualTo("I like cheese"); } @Test @@ -176,7 +169,7 @@ public void testWillSimulateAKeyDownWhenEnteringTextIntoInputElements() { WebElement result = driver.findElement(By.id("result")); // Because the key down gets the result before the input element is // filled, we're a letter short here - assertThat(result.getText(), equalTo("I like chees")); + assertThat(result.getText()).isEqualTo("I like chees"); } @Test @@ -190,7 +183,7 @@ public void testWillSimulateAKeyPressWhenEnteringTextIntoInputElements() { WebElement result = driver.findElement(By.id("result")); // Because the key down gets the result before the input element is // filled, we're a letter short here - assertThat(result.getText(), equalTo("I like chees")); + assertThat(result.getText()).isEqualTo("I like chees"); } @Test @@ -202,7 +195,7 @@ public void testWillSimulateAKeyUpWhenEnteringTextIntoTextAreas() { element.sendKeys("I like cheese"); WebElement result = driver.findElement(By.id("result")); - assertThat(result.getText(), equalTo("I like cheese")); + assertThat(result.getText()).isEqualTo("I like cheese"); } @Test @@ -216,7 +209,7 @@ public void testWillSimulateAKeyDownWhenEnteringTextIntoTextAreas() { WebElement result = driver.findElement(By.id("result")); // Because the key down gets the result before the input element is // filled, we're a letter short here - assertThat(result.getText(), equalTo("I like chees")); + assertThat(result.getText()).isEqualTo("I like chees"); } @Test @@ -230,7 +223,7 @@ public void testWillSimulateAKeyPressWhenEnteringTextIntoTextAreas() { WebElement result = driver.findElement(By.id("result")); // Because the key down gets the result before the input element is // filled, we're a letter short here - assertThat(result.getText(), equalTo("I like chees")); + assertThat(result.getText()).isEqualTo("I like chees"); } @Test @@ -242,13 +235,13 @@ public void testShouldFireFocusKeyEventsInTheRightOrder() { WebElement element = driver.findElement(By.id("theworks")); element.sendKeys("a"); - assertThat(result.getText().trim(), is("focus keydown keypress keyup")); + assertThat(result.getText().trim()).isEqualTo("focus keydown keypress keyup"); } private static void checkRecordedKeySequence(WebElement element, int expectedKeyCode) { - assertThat(element.getText().trim(), - anyOf(is(String.format("down: %1$d press: %1$d up: %1$d", expectedKeyCode)), - is(String.format("down: %1$d up: %1$d", expectedKeyCode)))); + assertThat(element.getText().trim()).isIn( + String.format("down: %1$d press: %1$d up: %1$d", expectedKeyCode), + String.format("down: %1$d up: %1$d", expectedKeyCode)); } @Test @@ -275,7 +268,7 @@ public void testShouldReportKeyCodeOfArrowKeys() { checkRecordedKeySequence(result, 39); // And leave no rubbish/printable keys in the "keyReporter" - assertThat(element.getAttribute("value"), is("")); + assertThat(element.getAttribute("value")).isEqualTo(""); } @Test @@ -289,23 +282,19 @@ public void testShouldReportKeyCodeOfArrowKeysUpDownEvents() { WebElement element = driver.findElement(By.id("keyReporter")); element.sendKeys(Keys.ARROW_DOWN); - assertThat(result.getText().trim(), containsString("down: 40")); - assertThat(result.getText().trim(), containsString("up: 40")); + assertThat(result.getText().trim()).contains("down: 40", "up: 40"); element.sendKeys(Keys.ARROW_UP); - assertThat(result.getText().trim(), containsString("down: 38")); - assertThat(result.getText().trim(), containsString("up: 38")); + assertThat(result.getText().trim()).contains("down: 38", "up: 38"); element.sendKeys(Keys.ARROW_LEFT); - assertThat(result.getText().trim(), containsString("down: 37")); - assertThat(result.getText().trim(), containsString("up: 37")); + assertThat(result.getText().trim()).contains("down: 37", "up: 37"); element.sendKeys(Keys.ARROW_RIGHT); - assertThat(result.getText().trim(), containsString("down: 39")); - assertThat(result.getText().trim(), containsString("up: 39")); + assertThat(result.getText().trim()).contains("down: 39", "up: 39"); // And leave no rubbish/printable keys in the "keyReporter" - assertThat(element.getAttribute("value"), is("")); + assertThat(element.getAttribute("value")).isEqualTo(""); } @Test @@ -317,7 +306,7 @@ public void testNumericNonShiftKeys() { String numericLineCharsNonShifted = "`1234567890-=[]\\;,.'/42"; element.sendKeys(numericLineCharsNonShifted); - assertThat(element.getAttribute("value"), is(numericLineCharsNonShifted)); + assertThat(element.getAttribute("value")).isEqualTo(numericLineCharsNonShifted); } @Test @@ -331,8 +320,8 @@ public void testNumericShiftKeys() { String numericShiftsEtc = "~!@#$%^&*()_+{}:\"<>?|END~"; element.sendKeys(numericShiftsEtc); - assertThat(element.getAttribute("value"), is(numericShiftsEtc)); - assertThat(result.getText().trim(), containsString(" up: 16")); + assertThat(element.getAttribute("value")).isEqualTo(numericShiftsEtc); + assertThat(result.getText().trim()).contains(" up: 16"); } @Test @@ -344,7 +333,7 @@ public void testLowerCaseAlphaKeys() { String lowerAlphas = "abcdefghijklmnopqrstuvwxyz"; element.sendKeys(lowerAlphas); - assertThat(element.getAttribute("value"), is(lowerAlphas)); + assertThat(element.getAttribute("value")).isEqualTo(lowerAlphas); } @Test @@ -358,8 +347,8 @@ public void testUppercaseAlphaKeys() { String upperAlphas = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; element.sendKeys(upperAlphas); - assertThat(element.getAttribute("value"), is(upperAlphas)); - assertThat(result.getText().trim(), containsString(" up: 16")); + assertThat(element.getAttribute("value")).isEqualTo(upperAlphas); + assertThat(result.getText().trim()).contains(" up: 16"); } @Test @@ -375,8 +364,8 @@ public void testAllPrintableKeys() { "PQRSTUVWXYZ [\\]^_`abcdefghijklmnopqrstuvwxyz{|}~"; element.sendKeys(allPrintable); - assertThat(element.getAttribute("value"), is(allPrintable)); - assertThat(result.getText().trim(), containsString(" up: 16")); + assertThat(element.getAttribute("value")).isEqualTo(allPrintable); + assertThat(result.getText().trim()).contains(" up: 16"); } @Test @@ -387,7 +376,7 @@ public void testArrowKeysAndPageUpAndDown() { element.sendKeys("a" + Keys.LEFT + "b" + Keys.RIGHT + Keys.UP + Keys.DOWN + Keys.PAGE_UP + Keys.PAGE_DOWN + "1"); - assertThat(element.getAttribute("value"), is("ba1")); + assertThat(element.getAttribute("value")).isEqualTo("ba1"); } @Test @@ -402,7 +391,7 @@ public void testHomeAndEndAndPageUpAndPageDownKeys() { element.sendKeys("abc" + Keys.HOME + "0" + Keys.LEFT + Keys.RIGHT + Keys.PAGE_UP + Keys.PAGE_DOWN + Keys.END + "1" + Keys.HOME + "0" + Keys.PAGE_UP + Keys.END + "111" + Keys.HOME + "00"); - assertThat(element.getAttribute("value"), is("0000abc1111")); + assertThat(element.getAttribute("value")).isEqualTo("0000abc1111"); } @Test @@ -412,13 +401,13 @@ public void testDeleteAndBackspaceKeys() { WebElement element = driver.findElement(By.id("keyReporter")); element.sendKeys("abcdefghi"); - assertThat(element.getAttribute("value"), is("abcdefghi")); + assertThat(element.getAttribute("value")).isEqualTo("abcdefghi"); element.sendKeys(Keys.LEFT, Keys.LEFT, Keys.DELETE); - assertThat(element.getAttribute("value"), is("abcdefgi")); + assertThat(element.getAttribute("value")).isEqualTo("abcdefgi"); element.sendKeys(Keys.LEFT, Keys.LEFT, Keys.BACK_SPACE); - assertThat(element.getAttribute("value"), is("abcdfgi")); + assertThat(element.getAttribute("value")).isEqualTo("abcdfgi"); } @Test @@ -429,7 +418,7 @@ public void testSpecialSpaceKeys() { WebElement element = driver.findElement(By.id("keyReporter")); element.sendKeys("abcd" + Keys.SPACE + "fgh" + Keys.SPACE + "ij"); - assertThat(element.getAttribute("value"), is("abcd fgh ij")); + assertThat(element.getAttribute("value")).isEqualTo("abcd fgh ij"); } @Test @@ -444,7 +433,7 @@ public void testNumberpadKeys() { Keys.DECIMAL + Keys.SEPARATOR + Keys.NUMPAD0 + Keys.NUMPAD9 + Keys.ADD + Keys.SEMICOLON + Keys.EQUALS + Keys.DIVIDE + Keys.NUMPAD3 + "abcd"); - assertThat(element.getAttribute("value"), is("abcd*-+.,09+;=/3abcd")); + assertThat(element.getAttribute("value")).isEqualTo("abcd*-+.,09+;=/3abcd"); } @Test @@ -456,7 +445,7 @@ public void testFunctionKeys() { element.sendKeys("FUNCTION" + Keys.F4 + "-KEYS" + Keys.F4); element.sendKeys("" + Keys.F4 + "-TOO" + Keys.F4); - assertThat(element.getAttribute("value"), is("FUNCTION-KEYS-TOO")); + assertThat(element.getAttribute("value")).isEqualTo("FUNCTION-KEYS-TOO"); } @Test @@ -467,11 +456,11 @@ public void testShiftSelectionDeletes() { WebElement element = driver.findElement(By.id("keyReporter")); element.sendKeys("abcd efgh"); - assertThat(element.getAttribute("value"), is("abcd efgh")); + assertThat(element.getAttribute("value")).isEqualTo("abcd efgh"); element.sendKeys(Keys.SHIFT, Keys.LEFT, Keys.LEFT, Keys.LEFT); element.sendKeys(Keys.DELETE); - assertThat(element.getAttribute("value"), is("abcd e")); + assertThat(element.getAttribute("value")).isEqualTo("abcd e"); } @Test @@ -489,10 +478,10 @@ public void testChordControlHomeShiftEndDelete() { element.sendKeys(Keys.HOME); element.sendKeys("" + Keys.SHIFT + Keys.END); - assertThat(result.getText(), containsString(" up: 16")); + assertThat(result.getText()).contains(" up: 16"); element.sendKeys(Keys.DELETE); - assertThat(element.getAttribute("value"), is("")); + assertThat(element.getAttribute("value")).isEqualTo(""); } @Test @@ -507,21 +496,20 @@ public void testChordReveseShiftHomeSelectionDeletes() { WebElement element = driver.findElement(By.id("keyReporter")); element.sendKeys("done" + Keys.HOME); - assertThat(element.getAttribute("value"), is("done")); + assertThat(element.getAttribute("value")).isEqualTo("done"); element.sendKeys(Keys.SHIFT + "ALL " + Keys.HOME); - assertThat(element.getAttribute("value"), is("ALL done")); + assertThat(element.getAttribute("value")).isEqualTo("ALL done"); element.sendKeys(Keys.DELETE); - assertThat(element.getAttribute("value"), is("done")); + assertThat(element.getAttribute("value")).isEqualTo("done"); element.sendKeys("" + Keys.END + Keys.SHIFT + Keys.HOME); - assertThat(element.getAttribute("value"), is("done")); - assertThat( // Note: trailing SHIFT up here - result.getText().trim(), containsString(" up: 16")); + assertThat(element.getAttribute("value")).isEqualTo("done"); + assertThat(result.getText().trim()).contains(" up: 16"); element.sendKeys(Keys.DELETE); - assertThat(element.getAttribute("value"), is("")); + assertThat(element.getAttribute("value")).isEqualTo(""); } // control-x control-v here for cut & paste tests, these work on windows @@ -540,14 +528,14 @@ public void testChordControlCutAndPaste() { String paste = "!\"#$%&'()*+,-./0123456789:;<=>?@ ABCDEFG"; element.sendKeys(paste); - assertThat(element.getAttribute("value"), is(paste)); + assertThat(element.getAttribute("value")).isEqualTo(paste); element.sendKeys(Keys.HOME); element.sendKeys("" + Keys.SHIFT + Keys.END); - assertThat(result.getText().trim(), containsString(" up: 16")); + assertThat(result.getText().trim()).contains(" up: 16"); element.sendKeys(Keys.CONTROL, "x"); - assertThat(element.getAttribute("value"), is("")); + assertThat(element.getAttribute("value")).isEqualTo(""); element.sendKeys(Keys.CONTROL, "v"); wait.until(elementValueToEqual(element, paste)); @@ -557,21 +545,21 @@ public void testChordControlCutAndPaste() { Keys.SHIFT + Keys.END); element.sendKeys(Keys.CONTROL, "x"); - assertThat(element.getAttribute("value"), is(paste.substring(0, paste.length() - 3))); + assertThat(element.getAttribute("value")).isEqualTo(paste.substring(0, paste.length() - 3)); // Paste the last 3 letters. element.sendKeys(Keys.CONTROL, "v"); - assertThat(element.getAttribute("value"), is(paste)); + assertThat(element.getAttribute("value")).isEqualTo(paste); element.sendKeys(Keys.HOME); element.sendKeys(Keys.CONTROL, "v"); element.sendKeys(Keys.CONTROL, "v" + "v"); element.sendKeys(Keys.CONTROL, "v" + "v" + "v"); - assertThat(element.getAttribute("value"), is("EFGEFGEFGEFGEFGEFG" + paste)); + assertThat(element.getAttribute("value")).isEqualTo("EFGEFGEFGEFGEFGEFG" + paste); element.sendKeys("" + Keys.END + Keys.SHIFT + Keys.HOME + Keys.NULL + Keys.DELETE); - assertThat(element.getAttribute("value"), is("")); + assertThat(element.getAttribute("value")).isEqualTo(""); } @Test @@ -581,7 +569,7 @@ public void testShouldTypeIntoInputElementsThatHaveNoTypeAttribute() { WebElement element = driver.findElement(By.id("no-type")); element.sendKeys("should say cheese"); - assertThat(element.getAttribute("value"), is("should say cheese")); + assertThat(element.getAttribute("value")).isEqualTo("should say cheese"); } @Test @@ -591,7 +579,7 @@ public void testShouldNotTypeIntoElementsThatPreventKeyDownEvents() { WebElement silent = driver.findElement(By.name("suppress")); silent.sendKeys("s"); - assertThat(silent.getAttribute("value"), is("")); + assertThat(silent.getAttribute("value")).isEqualTo(""); } @Test @@ -604,7 +592,7 @@ public void testGenerateKeyPressEventEvenWhenElementPreventsDefault() { WebElement result = driver.findElement(By.id("result")); silent.sendKeys("s"); - assertThat(result.getText().trim(), is("")); + assertThat(result.getText().trim()).isEqualTo(""); } @Test @@ -612,7 +600,7 @@ public void testShouldBeAbleToTypeOnAnEmailInputField() { driver.get(pages.formPage); WebElement email = driver.findElement(By.id("email")); email.sendKeys("foobar"); - assertThat(email.getAttribute("value"), equalTo("foobar")); + assertThat(email.getAttribute("value")).isEqualTo("foobar"); } @Test @@ -620,15 +608,15 @@ public void testShouldBeAbleToTypeOnANumberInputField() { driver.get(pages.formPage); WebElement email = driver.findElement(By.id("age")); email.sendKeys("33"); - assertThat(email.getAttribute("value"), equalTo("33")); + assertThat(email.getAttribute("value")).isEqualTo("33"); } @Test public void testShouldThrowIllegalArgumentException() { driver.get(pages.formPage); WebElement email = driver.findElement(By.id("age")); - Throwable t = catchThrowable(() -> email.sendKeys((CharSequence[]) null)); - assertThat(t, instanceOf(IllegalArgumentException.class)); + assertThatExceptionOfType(IllegalArgumentException.class) + .isThrownBy(() -> email.sendKeys((CharSequence[]) null)); } @Test @@ -638,26 +626,26 @@ public void canSafelyTypeOnElementThatIsRemovedFromTheDomOnKeyPress() { WebElement input = driver.findElement(By.id("target")); WebElement log = driver.findElement(By.id("log")); - assertEquals("", log.getAttribute("value")); + assertThat(log.getAttribute("value")).isEqualTo(""); input.sendKeys("b"); - assertThat(getValueText(log), equalTo(Joiner.on('\n').join( + assertThat(getValueText(log)).isEqualTo(on('\n').join( "keydown (target)", "keyup (target)", - "keyup (body)"))); + "keyup (body)")); input.sendKeys("a"); // Some drivers (IE, Firefox) do not always generate the final keyup event since the element // is removed from the DOM in response to the keypress (note, this is a product of how events // are generated and does not match actual user behavior). - String expected = Joiner.on('\n').join( + String expected = String.join("\n", "keydown (target)", "keyup (target)", "keyup (body)", "keydown (target)", "a pressed; removing"); - assertThat(getValueText(log), anyOf(equalTo(expected), equalTo(expected + "\nkeyup (body)"))); + assertThat(getValueText(log)).isIn(expected, expected + "\nkeyup (body)"); } @Test @@ -667,7 +655,7 @@ public void canClearNumberInputAfterTypingInvalidInput() { input.sendKeys("e"); input.clear(); input.sendKeys("3"); - assertEquals("3", input.getAttribute("value")); + assertThat(input.getAttribute("value")).isEqualTo("3"); } private static String getValueText(WebElement el) { diff --git a/java/client/test/org/openqa/selenium/UnexpectedAlertBehaviorTest.java b/java/client/test/org/openqa/selenium/UnexpectedAlertBehaviorTest.java index 9632152d2ac66..30c09f7c6de9e 100644 --- a/java/client/test/org/openqa/selenium/UnexpectedAlertBehaviorTest.java +++ b/java/client/test/org/openqa/selenium/UnexpectedAlertBehaviorTest.java @@ -17,8 +17,8 @@ package org.openqa.selenium; -import static org.hamcrest.Matchers.instanceOf; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.openqa.selenium.UnexpectedAlertBehaviour.IGNORE; import static org.openqa.selenium.WaitingConditions.elementTextToEqual; import static org.openqa.selenium.remote.CapabilityType.UNEXPECTED_ALERT_BEHAVIOUR; import static org.openqa.selenium.testing.Driver.CHROME; @@ -26,7 +26,6 @@ import static org.openqa.selenium.testing.Driver.HTMLUNIT; import static org.openqa.selenium.testing.Driver.MARIONETTE; import static org.openqa.selenium.testing.Driver.SAFARI; -import static org.openqa.selenium.testing.TestUtilities.catchThrowable; import org.junit.After; import org.junit.Test; @@ -90,9 +89,8 @@ public void canDismissUnhandledAlertsByDefault() { @Test @Ignore(value = CHROME, reason = "Unstable Chrome behavior") public void canIgnoreUnhandledAlert() { - Throwable t = catchThrowable( - () -> runScenarioWithUnhandledAlert(UnexpectedAlertBehaviour.IGNORE, "Text ignored", true)); - assertThat(t, instanceOf(UnhandledAlertException.class)); + assertThatExceptionOfType(UnhandledAlertException.class).isThrownBy( + () -> runScenarioWithUnhandledAlert(IGNORE, "Text ignored", true)); driver2.switchTo().alert().dismiss(); } diff --git a/java/client/test/org/openqa/selenium/UploadTest.java b/java/client/test/org/openqa/selenium/UploadTest.java index 52660d4145ed6..b0d8bfefc00d4 100644 --- a/java/client/test/org/openqa/selenium/UploadTest.java +++ b/java/client/test/org/openqa/selenium/UploadTest.java @@ -17,9 +17,8 @@ package org.openqa.selenium; -import static org.hamcrest.CoreMatchers.instanceOf; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assume.assumeFalse; import static org.openqa.selenium.Platform.ANDROID; import static org.openqa.selenium.WaitingConditions.elementTextToEqual; @@ -29,7 +28,6 @@ import static org.openqa.selenium.testing.Driver.HTMLUNIT; import static org.openqa.selenium.testing.Driver.IE; import static org.openqa.selenium.testing.Driver.SAFARI; -import static org.openqa.selenium.testing.TestUtilities.catchThrowable; import com.google.common.io.Files; @@ -90,7 +88,7 @@ public void testCleanFileInput() { WebElement element = driver.findElement(By.id("upload")); element.sendKeys(testFile.getAbsolutePath()); element.clear(); - assertEquals("", element.getAttribute("value")); + assertThat(element.getAttribute("value")).isEqualTo(""); } @Test @@ -101,8 +99,7 @@ public void testCleanFileInput() { public void testClickFileInput() { driver.get(pages.uploadPage); WebElement element = driver.findElement(By.id("upload")); - Throwable ex = catchThrowable(element::click); - assertThat(ex, instanceOf(InvalidArgumentException.class)); + assertThatExceptionOfType(InvalidArgumentException.class).isThrownBy(element::click); } @Test diff --git a/java/client/test/org/openqa/selenium/VisibilityTest.java b/java/client/test/org/openqa/selenium/VisibilityTest.java index e44db78a8e2f2..36c56df301dd3 100644 --- a/java/client/test/org/openqa/selenium/VisibilityTest.java +++ b/java/client/test/org/openqa/selenium/VisibilityTest.java @@ -17,13 +17,8 @@ package org.openqa.selenium; -import static org.hamcrest.Matchers.instanceOf; -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.assertThat; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assume.assumeFalse; import static org.openqa.selenium.Platform.ANDROID; import static org.openqa.selenium.support.ui.ExpectedConditions.not; @@ -31,7 +26,6 @@ import static org.openqa.selenium.testing.Driver.HTMLUNIT; import static org.openqa.selenium.testing.Driver.IE; import static org.openqa.selenium.testing.Driver.SAFARI; -import static org.openqa.selenium.testing.TestUtilities.catchThrowable; import org.junit.Test; import org.openqa.selenium.testing.Ignore; @@ -47,10 +41,10 @@ public class VisibilityTest extends JUnit4TestBase { public void testShouldAllowTheUserToTellIfAnElementIsDisplayedOrNot() { driver.get(pages.javascriptPage); - assertTrue(driver.findElement(By.id("displayed")).isDisplayed()); - assertFalse(driver.findElement(By.id("none")).isDisplayed()); - assertFalse(driver.findElement(By.id("suppressedParagraph")).isDisplayed()); - assertFalse(driver.findElement(By.id("hidden")).isDisplayed()); + assertThat(driver.findElement(By.id("displayed")).isDisplayed()).isTrue(); + assertThat(driver.findElement(By.id("none")).isDisplayed()).isFalse(); + assertThat(driver.findElement(By.id("suppressedParagraph")).isDisplayed()).isFalse(); + assertThat(driver.findElement(By.id("hidden")).isDisplayed()).isFalse(); } @Test @@ -60,8 +54,8 @@ public void testVisibilityShouldTakeIntoAccountParentVisibility() { WebElement childDiv = driver.findElement(By.id("hiddenchild")); WebElement hiddenLink = driver.findElement(By.id("hiddenlink")); - assertFalse(childDiv.isDisplayed()); - assertFalse(hiddenLink.isDisplayed()); + assertThat(childDiv.isDisplayed()).isFalse(); + assertThat(hiddenLink.isDisplayed()).isFalse(); } @Test @@ -70,7 +64,7 @@ public void testShouldCountElementsAsVisibleIfStylePropertyHasBeenSet() { WebElement shown = driver.findElement(By.id("visibleSubElement")); - assertTrue(shown.isDisplayed()); + assertThat(shown.isDisplayed()).isTrue(); } @Test @@ -79,13 +73,13 @@ public void testShouldModifyTheVisibilityOfAnElementDynamically() { WebElement element = driver.findElement(By.id("hideMe")); - assertTrue(element.isDisplayed()); + assertThat(element.isDisplayed()).isTrue(); element.click(); wait.until(not(visibilityOf(element))); - assertFalse(element.isDisplayed()); + assertThat(element.isDisplayed()).isFalse(); } @Test @@ -94,7 +88,7 @@ public void testHiddenInputElementsAreNeverVisible() { WebElement shown = driver.findElement(By.name("hidden")); - assertFalse(shown.isDisplayed()); + assertThat(shown.isDisplayed()).isFalse(); } @Test @@ -102,8 +96,7 @@ public void testShouldNotBeAbleToClickOnAnElementThatIsNotDisplayed() { driver.get(pages.javascriptPage); WebElement element = driver.findElement(By.id("unclickable")); - Throwable t = catchThrowable(element::click); - assertThat(t, instanceOf(ElementNotInteractableException.class)); + assertThatExceptionOfType(ElementNotInteractableException.class).isThrownBy(element::click); } @Test @@ -111,9 +104,9 @@ public void testShouldNotBeAbleToTypeToAnElementThatIsNotDisplayed() { driver.get(pages.javascriptPage); WebElement element = driver.findElement(By.id("unclickable")); - Throwable t = catchThrowable(() -> element.sendKeys("You don't see me")); - assertThat(t, instanceOf(ElementNotInteractableException.class)); - assertThat(element.getAttribute("value"), is(not("You don't see me"))); + assertThatExceptionOfType(ElementNotInteractableException.class) + .isThrownBy(() -> element.sendKeys("You don't see me")); + assertThat(element.getAttribute("value")).isNotEqualTo("You don't see me"); } @Test @@ -124,9 +117,9 @@ public void testZeroSizedDivIsShownIfDescendantHasSize() { WebElement element = driver.findElement(By.id("zero")); Dimension size = element.getSize(); - assertEquals("Should have 0 width", 0, size.width); - assertEquals("Should have 0 height", 0, size.height); - assertTrue(element.isDisplayed()); + assertThat(size.width).isEqualTo(0); + assertThat(size.height).isEqualTo(0); + assertThat(element.isDisplayed()).isTrue(); } @Test @@ -135,7 +128,7 @@ public void parentNodeVisibleWhenAllChildrenAreAbsolutelyPositionedAndOverflowIs driver.get(url); WebElement element = driver.findElement(By.id("suggest")); - assertTrue(element.isDisplayed()); + assertThat(element.isDisplayed()).isTrue(); } @Test @@ -151,9 +144,9 @@ public void testElementHiddenByOverflowXIsNotVisible() { for (String page: pages) { driver.get(appServer.whereIs(page)); WebElement right = driver.findElement(By.id("right")); - assertFalse(page, right.isDisplayed()); + assertThat(right.isDisplayed()).as("On page %s", page).isFalse(); WebElement bottomRight = driver.findElement(By.id("bottom-right")); - assertFalse(page, bottomRight.isDisplayed()); + assertThat(bottomRight.isDisplayed()).as("On page %s", page).isFalse(); } } @@ -169,9 +162,9 @@ public void testElementHiddenByOverflowYIsNotVisible() { for (String page: pages) { driver.get(appServer.whereIs(page)); WebElement bottom = driver.findElement(By.id("bottom")); - assertFalse(page, bottom.isDisplayed()); + assertThat(bottom.isDisplayed()).as("On page %s", page).isFalse(); WebElement bottomRight = driver.findElement(By.id("bottom-right")); - assertFalse(page, bottomRight.isDisplayed()); + assertThat(bottomRight.isDisplayed()).as("On page %s", page).isFalse(); } } @@ -189,7 +182,7 @@ public void testElementScrollableByOverflowXIsVisible() { for (String page: pages) { driver.get(appServer.whereIs(page)); WebElement right = driver.findElement(By.id("right")); - assertTrue(page, right.isDisplayed()); + assertThat(right.isDisplayed()).as("On page %s", page).isTrue(); } } @@ -207,7 +200,7 @@ public void testElementScrollableByOverflowYIsVisible() { for (String page: pages) { driver.get(appServer.whereIs(page)); WebElement bottom = driver.findElement(By.id("bottom")); - assertTrue(page, bottom.isDisplayed()); + assertThat(bottom.isDisplayed()).as("On page %s", page).isTrue(); } } @@ -222,7 +215,7 @@ public void testElementScrollableByOverflowXAndYIsVisible() { for (String page: pages) { driver.get(appServer.whereIs(page)); WebElement bottomRight = driver.findElement(By.id("bottom-right")); - assertTrue(page, bottomRight.isDisplayed()); + assertThat(bottomRight.isDisplayed()).as("On page %s", page).isTrue(); } } @@ -242,7 +235,7 @@ public void tooSmallAWindowWithOverflowHiddenIsNotAProblem() { driver.get(url); WebElement element = driver.findElement(By.name("resultsFrame")); - assertTrue(element.isDisplayed()); + assertThat(element.isDisplayed()).isTrue(); } finally { window.setSize(originalSize); } @@ -254,7 +247,7 @@ public void shouldShowElementNotVisibleWithHiddenAttribute() { String url = appServer.whereIs("hidden.html"); driver.get(url); WebElement element = driver.findElement(By.id("singleHidden")); - assertFalse(element.isDisplayed()); + assertThat(element.isDisplayed()).isFalse(); } @Test @@ -264,7 +257,7 @@ public void testShouldShowElementNotVisibleWhenParentElementHasHiddenAttribute() driver.get(url); WebElement element = driver.findElement(By.id("child")); - assertFalse(element.isDisplayed()); + assertThat(element.isDisplayed()).isFalse(); } /** @@ -278,10 +271,10 @@ public void testShouldBeAbleToClickOnElementsWithOpacityZero() { driver.get(pages.clickJacker); WebElement element = driver.findElement(By.id("clickJacker")); - assertEquals("Precondition failed: clickJacker should be transparent", - "0", element.getCssValue("opacity")); + assertThat(element.getCssValue("opacity")) + .describedAs("Precondition failed: clickJacker should be transparent").isEqualTo("0"); element.click(); - assertEquals("1", element.getCssValue("opacity")); + assertThat(element.getCssValue("opacity")).isEqualTo("1"); } @Test @@ -295,12 +288,12 @@ public void testShouldBeAbleToSelectOptionsFromAnInvisibleSelect() { WebElement apples = options.get(0); WebElement oranges = options.get(1); - assertTrue("Apples should be selected", apples.isSelected()); - assertFalse("Oranges should be selected", oranges.isSelected()); + assertThat(apples.isSelected()).as("Apples").isTrue(); + assertThat(oranges.isSelected()).as("Oranges").isFalse(); oranges.click(); - assertFalse("Apples should not be selected", apples.isSelected()); - assertTrue("Oranges should be selected", oranges.isSelected()); + assertThat(apples.isSelected()).as("Apples").isFalse(); + assertThat(oranges.isSelected()).as("Oranges").isTrue(); } @Test @@ -310,8 +303,7 @@ public void testCorrectlyDetectMapElementsAreShown() { final WebElement area = driver.findElement(By.id("mtgt_unnamed_0")); - boolean isShown = area.isDisplayed(); - assertTrue("The element and the enclosing map should be considered shown.", isShown); + assertThat(area.isDisplayed()).as("The element and the enclosing map").isTrue(); } } diff --git a/java/client/test/org/openqa/selenium/WebDriverExceptionTest.java b/java/client/test/org/openqa/selenium/WebDriverExceptionTest.java index 45e307c0bb0d8..0b81a8537659d 100644 --- a/java/client/test/org/openqa/selenium/WebDriverExceptionTest.java +++ b/java/client/test/org/openqa/selenium/WebDriverExceptionTest.java @@ -16,16 +16,13 @@ // under the License. package org.openqa.selenium; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; /** * Small test for name extraction */ -@RunWith(JUnit4.class) public class WebDriverExceptionTest { @Test public void testExtractsADriverName() { @@ -35,7 +32,7 @@ public void testExtractsADriverName() { String gotName = WebDriverException.getDriverName(stackTrace); - assertEquals("TestDriver", gotName); + assertThat(gotName).isEqualTo("TestDriver"); } @Test @@ -48,8 +45,7 @@ public void testExtractsMostSpecificDriverName() { String gotName = WebDriverException.getDriverName(stackTrace); - assertEquals("FirefoxDriver", gotName); - + assertThat(gotName).isEqualTo("FirefoxDriver"); } @Test @@ -60,7 +56,7 @@ public void testDefaultsToUnknownDriverName() { String gotName = WebDriverException.getDriverName(stackTrace); - assertEquals("unknown", gotName); + assertThat(gotName).isEqualTo("unknown"); } } diff --git a/java/client/test/org/openqa/selenium/WebElementTest.java b/java/client/test/org/openqa/selenium/WebElementTest.java index 6909f0fd81d3e..d157da03e53e1 100644 --- a/java/client/test/org/openqa/selenium/WebElementTest.java +++ b/java/client/test/org/openqa/selenium/WebElementTest.java @@ -17,7 +17,7 @@ package org.openqa.selenium; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; import org.openqa.selenium.testing.JUnit4TestBase; @@ -31,14 +31,14 @@ public class WebElementTest extends JUnit4TestBase { public void testElementImplementsWrapsDriver() { driver.get(pages.simpleTestPage); WebElement parent = driver.findElement(By.id("containsSomeDiv")); - assertTrue(parent instanceof WrapsDriver); + assertThat(parent).isInstanceOf(WrapsDriver.class); } @Test public void testElementReturnsOriginDriver() { driver.get(pages.simpleTestPage); WebElement parent = driver.findElement(By.id("containsSomeDiv")); - assertTrue(((WrapsDriver) parent).getWrappedDriver() == driver); + assertThat(((WrapsDriver) parent).getWrappedDriver()).isSameAs(driver); } } diff --git a/java/client/test/org/openqa/selenium/WindowSwitchingTest.java b/java/client/test/org/openqa/selenium/WindowSwitchingTest.java index fba36577a2aef..f90187f87ab11 100644 --- a/java/client/test/org/openqa/selenium/WindowSwitchingTest.java +++ b/java/client/test/org/openqa/selenium/WindowSwitchingTest.java @@ -17,11 +17,8 @@ package org.openqa.selenium; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.instanceOf; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assume.assumeFalse; import static org.openqa.selenium.Platform.ANDROID; import static org.openqa.selenium.WaitingConditions.newWindowIsOpened; @@ -31,7 +28,8 @@ import static org.openqa.selenium.testing.Driver.IE; import static org.openqa.selenium.testing.Driver.MARIONETTE; import static org.openqa.selenium.testing.Driver.SAFARI; -import static org.openqa.selenium.testing.TestUtilities.catchThrowable; +import static org.openqa.selenium.testing.TestUtilities.isIe6; +import static org.openqa.selenium.testing.TestUtilities.isInternetExplorer; import org.junit.Rule; import org.junit.Test; @@ -91,23 +89,23 @@ public void testShouldSwitchFocusToANewWindowWhenItIsOpenedAndNotStopFutureOpera wait.until(newWindowIsOpened(currentWindowHandles)); - assertThat(driver.getTitle(), equalTo("XHTML Test Page")); + assertThat(driver.getTitle()).isEqualTo("XHTML Test Page"); driver.switchTo().window("result"); - assertThat(driver.getTitle(), equalTo("We Arrive Here")); + assertThat(driver.getTitle()).isEqualTo("We Arrive Here"); driver.get(pages.iframePage); final String handle = driver.getWindowHandle(); driver.findElement(By.id("iframe_page_heading")); driver.switchTo().frame("iframe1"); - assertThat(driver.getWindowHandle(), equalTo(handle)); + assertThat(driver.getWindowHandle()).isEqualTo(handle); } @Test public void testShouldThrowNoSuchWindowException() { driver.get(pages.xhtmlTestPage); - Throwable t = catchThrowable(() -> driver.switchTo().window("invalid name")); - assertThat(t, instanceOf(NoSuchWindowException.class)); + assertThatExceptionOfType(NoSuchWindowException.class) + .isThrownBy(() -> driver.switchTo().window("invalid name")); } @NoDriverAfterTest(failedOnly = true) @@ -123,8 +121,7 @@ public void testShouldThrowNoSuchWindowExceptionOnAnAttemptToGetItsHandle() { driver.switchTo().window("result"); driver.close(); - Throwable t = catchThrowable(driver::getWindowHandle); - assertThat(t, instanceOf(NoSuchWindowException.class)); + assertThatExceptionOfType(NoSuchWindowException.class).isThrownBy(driver::getWindowHandle); } @NoDriverAfterTest(failedOnly = true) @@ -140,11 +137,10 @@ public void testShouldThrowNoSuchWindowExceptionOnAnyOperationIfAWindowIsClosed( driver.switchTo().window("result"); driver.close(); - Throwable t = catchThrowable(driver::getTitle); - assertThat(t, instanceOf(NoSuchWindowException.class)); + assertThatExceptionOfType(NoSuchWindowException.class).isThrownBy(driver::getTitle); - Throwable t2 = catchThrowable(() -> driver.findElement(By.tagName("body"))); - assertThat(t2, instanceOf(NoSuchWindowException.class)); + assertThatExceptionOfType(NoSuchWindowException.class) + .isThrownBy(() -> driver.findElement(By.tagName("body"))); } @NoDriverAfterTest(failedOnly = true) @@ -161,8 +157,7 @@ public void testShouldThrowNoSuchWindowExceptionOnAnyElementOperationIfAWindowIs WebElement body = driver.findElement(By.tagName("body")); driver.close(); - Throwable t = catchThrowable(body::getText); - assertThat(t, instanceOf(NoSuchWindowException.class)); + assertThatExceptionOfType(NoSuchWindowException.class).isThrownBy(body::getText); } @NoDriverAfterTest @@ -185,8 +180,8 @@ public void testShouldBeAbleToIterateOverAllOpenWindows() { return driver.getTitle(); }).collect(Collectors.toSet()); - assertEquals(3, allWindowHandles.size()); - assertEquals(3, allWindowTitles.size()); + assertThat(allWindowHandles).hasSize(3); + assertThat(allWindowTitles).hasSize(3); } @Test @@ -197,8 +192,6 @@ public void testClickingOnAButtonThatClosesAnOpenWindowDoesNotCauseTheBrowserToH TestUtilities.getEffectivePlatform().is(Platform.WINDOWS)); driver.get(pages.xhtmlTestPage); - Boolean isIEDriver = TestUtilities.isInternetExplorer(driver); - Boolean isIE6 = TestUtilities.isIe6(driver); Set currentWindowHandles = driver.getWindowHandles(); driver.findElement(By.name("windowThree")).click(); @@ -214,7 +207,7 @@ public void testClickingOnAButtonThatClosesAnOpenWindowDoesNotCauseTheBrowserToH wait.until(ExpectedConditions.presenceOfElementLocated(By.id("close"))).click(); - if (isIEDriver && !isIE6) { + if (isInternetExplorer(driver) && !isIe6(driver)) { Alert alert = wait.until(alertIsPresent()); alert.accept(); } @@ -230,8 +223,6 @@ public void testCanCallGetWindowHandlesAfterClosingAWindow() throws Exception { driver.get(pages.xhtmlTestPage); - Boolean isIEDriver = TestUtilities.isInternetExplorer(driver); - Boolean isIE6 = TestUtilities.isIe6(driver); Set currentWindowHandles = driver.getWindowHandles(); driver.findElement(By.name("windowThree")).click(); @@ -248,20 +239,20 @@ public void testCanCallGetWindowHandlesAfterClosingAWindow() throws Exception { wait.until(ExpectedConditions.presenceOfElementLocated(By.id("close"))).click(); - if (isIEDriver && !isIE6) { + if (isInternetExplorer(driver) && !isIe6(driver)) { Alert alert = wait.until(alertIsPresent()); alert.accept(); } Set allHandles = wait.until(windowHandleCountToBe(allWindowHandles - 1)); - assertEquals(currentWindowHandles.size(), allHandles.size()); + assertThat(allHandles).hasSameSizeAs(currentWindowHandles); } @Test public void testCanObtainAWindowHandle() { driver.get(pages.xhtmlTestPage); - assertNotNull(driver.getWindowHandle()); + assertThat(driver.getWindowHandle()).isNotNull(); } @Test @@ -269,11 +260,11 @@ public void testFailingToSwitchToAWindowLeavesTheCurrentWindowAsIs() { driver.get(pages.xhtmlTestPage); String current = driver.getWindowHandle(); - Throwable t = catchThrowable(() -> driver.switchTo().window("i will never exist")); - assertThat(t, instanceOf(NoSuchWindowException.class)); + assertThatExceptionOfType(NoSuchWindowException.class) + .isThrownBy(() -> driver.switchTo().window("i will never exist")); String newHandle = driver.getWindowHandle(); - assertEquals(current, newHandle); + assertThat(newHandle).isEqualTo(current); } @NoDriverAfterTest(failedOnly = true) @@ -291,14 +282,14 @@ public void testCanCloseWindowWhenMultipleWindowsAreOpen() { Set allWindowHandles = driver.getWindowHandles(); // There should be two windows. We should also see each of the window titles at least once. - assertEquals(2, allWindowHandles.size()); + assertThat(allWindowHandles).hasSize(2); allWindowHandles.stream().filter(anObject -> ! mainHandle.equals(anObject)).forEach(handle -> { driver.switchTo().window(handle); driver.close(); }); - assertEquals(1, driver.getWindowHandles().size()); + assertThat(driver.getWindowHandles()).hasSize(1); } @NoDriverAfterTest(failedOnly = true) @@ -316,7 +307,7 @@ public void testCanCloseWindowAndSwitchBackToMainWindow() { Set allWindowHandles = driver.getWindowHandles(); // There should be two windows. We should also see each of the window titles at least once. - assertEquals(2, allWindowHandles.size()); + assertThat(allWindowHandles).hasSize(2); allWindowHandles.stream().filter(anObject -> ! mainHandle.equals(anObject)).forEach(handle -> { driver.switchTo().window(handle); @@ -326,9 +317,9 @@ public void testCanCloseWindowAndSwitchBackToMainWindow() { driver.switchTo().window(mainHandle); String newHandle = driver.getWindowHandle(); - assertEquals(mainHandle, newHandle); + assertThat(newHandle).isEqualTo(mainHandle); - assertEquals(1, driver.getWindowHandles().size()); + assertThat(driver.getWindowHandles()).hasSize(1); } @NoDriverAfterTest diff --git a/java/client/test/org/openqa/selenium/WindowTest.java b/java/client/test/org/openqa/selenium/WindowTest.java index 66ff6f793febf..c923a692bf11e 100644 --- a/java/client/test/org/openqa/selenium/WindowTest.java +++ b/java/client/test/org/openqa/selenium/WindowTest.java @@ -17,10 +17,7 @@ package org.openqa.selenium; -import static org.hamcrest.Matchers.greaterThan; -import static org.hamcrest.Matchers.greaterThanOrEqualTo; -import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assume.assumeFalse; import static org.openqa.selenium.Platform.ANDROID; import static org.openqa.selenium.Platform.LINUX; @@ -44,8 +41,8 @@ public void testGetsTheSizeOfTheCurrentWindow() { TestUtilities.isChrome(driver) && TestUtilities.getEffectivePlatform(driver).is(ANDROID)); Dimension size = driver.manage().window().getSize(); - assertThat(size.width, is(greaterThan(0))); - assertThat(size.height, is(greaterThan(0))); + assertThat(size.width).isGreaterThan(0); + assertThat(size.height).isGreaterThan(0); } @Test @@ -100,8 +97,8 @@ public void testGetsThePositionOfTheCurrentWindow() { // If the Chrome under test is launched by default as maximized, the window // coordinates may have small negative values (note that elements in the // viewport are, of course, still clickable). - assertThat(position.x, is(greaterThanOrEqualTo(-10))); - assertThat(position.y, is(greaterThanOrEqualTo(-10))); + assertThat(position.x).isGreaterThanOrEqualTo(-10); + assertThat(position.y).isGreaterThanOrEqualTo(-10); } @Test diff --git a/java/client/test/org/openqa/selenium/atoms/CompiledAtomsNotLeakingTest.java b/java/client/test/org/openqa/selenium/atoms/CompiledAtomsNotLeakingTest.java index 4366491a662e6..7edbcf07be97f 100644 --- a/java/client/test/org/openqa/selenium/atoms/CompiledAtomsNotLeakingTest.java +++ b/java/client/test/org/openqa/selenium/atoms/CompiledAtomsNotLeakingTest.java @@ -17,7 +17,7 @@ package org.openqa.selenium.atoms; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import com.google.gson.JsonObject; import com.google.gson.JsonParser; @@ -30,12 +30,9 @@ import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; import java.io.IOException; -@RunWith(JUnit4.class) public class CompiledAtomsNotLeakingTest { private static final String FRAGMENT_TASK = @@ -58,16 +55,16 @@ public void prepareGlobalObject() { ContextFactory.getGlobal().call(context -> { global = context.initStandardObjects(); global.defineProperty("_", 1234, ScriptableObject.EMPTY); - assertEquals(1234, eval(context, "_")); + assertThat(eval(context, "_")).isEqualTo(1234); // We're using the //javascript/webdriver/atoms:execute_script atom, // which assumes it is used in the context of a browser window, so make // sure the "window" free variable is defined and refers to the global // context. - assertEquals(global, eval(context, "this.window=this;")); - assertEquals(global, eval(context, "this")); - assertEquals(global, eval(context, "window")); - assertEquals(true, eval(context, "this === window")); + assertThat(eval(context, "this.window=this;")).isEqualTo(global); + assertThat(eval(context, "this")).isEqualTo(global); + assertThat(eval(context, "window")).isEqualTo(global); + assertThat(eval(context, "this === window")).isEqualTo(true); return null; }); @@ -78,22 +75,22 @@ public void prepareGlobalObject() { public void fragmentWillNotLeakVariablesToEnclosingScopes() { ContextFactory.getGlobal().call(context -> { eval(context, "(" + fragment + ")()", FRAGMENT_PATH); - assertEquals(1234, eval(context, "_")); + assertThat(eval(context, "_")).isEqualTo(1234); eval(context, "(" + fragment + ").call(this)", FRAGMENT_PATH); - assertEquals(1234, eval(context, "_")); + assertThat(eval(context, "_")).isEqualTo(1234); eval(context, "(" + fragment + ").apply(this,[])", FRAGMENT_PATH); - assertEquals(1234, eval(context, "_")); + assertThat(eval(context, "_")).isEqualTo(1234); eval(context, "(" + fragment + ").call(null)", FRAGMENT_PATH); - assertEquals(1234, eval(context, "_")); + assertThat(eval(context, "_")).isEqualTo(1234); eval(context, "(" + fragment + ").apply(null,[])", FRAGMENT_PATH); - assertEquals(1234, eval(context, "_")); + assertThat(eval(context, "_")).isEqualTo(1234); eval(context, "(" + fragment + ").call({})", FRAGMENT_PATH); - assertEquals(1234, eval(context, "_")); + assertThat(eval(context, "_")).isEqualTo(1234); return null; }); } @@ -112,17 +109,17 @@ public void nestedFragmentsShouldNotLeakVariables() { try { JsonObject result = new JsonParser().parse(jsonResult).getAsJsonObject(); - assertEquals(jsonResult, 0, result.get("status").getAsLong()); + assertThat(result.get("status").getAsLong()).as(jsonResult).isEqualTo(0); result = result.get("value").getAsJsonObject(); - assertEquals(jsonResult, 0, result.get("status").getAsLong()); - assertEquals(jsonResult, 3, result.get("value").getAsLong()); + assertThat(result.get("status").getAsLong()).as(jsonResult).isEqualTo(0); + assertThat(result.get("value").getAsLong()).as(jsonResult).isEqualTo(3); } catch (JsonSyntaxException e) { throw new RuntimeException("JSON result was: " + jsonResult, e); } - assertEquals(1234, eval(context, "_")); + assertThat(eval(context, "_")).isEqualTo(1234); return null; }); } diff --git a/java/client/test/org/openqa/selenium/atoms/InputAtomsTest.java b/java/client/test/org/openqa/selenium/atoms/InputAtomsTest.java index ddeed1d98827e..4192c709f7b86 100644 --- a/java/client/test/org/openqa/selenium/atoms/InputAtomsTest.java +++ b/java/client/test/org/openqa/selenium/atoms/InputAtomsTest.java @@ -17,7 +17,7 @@ package org.openqa.selenium.atoms; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import net.sourceforge.htmlunit.corejs.javascript.Context; import net.sourceforge.htmlunit.corejs.javascript.ContextAction; @@ -50,10 +50,10 @@ public Object run(Context context) { global = context.initStandardObjects(); // Check assumptions abut the global context, which the atoms assumes is a DOM window. - assertEquals(global, eval(context, "this.window=this;")); - assertEquals(global, eval(context, "this")); - assertEquals(global, eval(context, "window")); - assertEquals(true, eval(context, "this === window")); + assertThat((Object) eval(context, "this.window=this;")).isEqualTo(global); + assertThat((Object) eval(context, "this")).isEqualTo(global); + assertThat((Object) eval(context, "window")).isEqualTo(global); + assertThat((Object) eval(context, "this === window")).isEqualTo(true); eval(context, source, JavaScriptLoader.taskToBuildOutput(RESOURCE_TASK)); @@ -69,10 +69,7 @@ public Object run(Context context) { } private void assertFunction(Context context, String property) { - assertEquals( - "Expected " + property + " to be a function", - "function", - eval(context, "typeof " + property)); + assertThat((Object) eval(context, "typeof " + property)).describedAs(property).isEqualTo("function"); } @SuppressWarnings({"unchecked"}) diff --git a/java/client/test/org/openqa/selenium/chrome/BUCK b/java/client/test/org/openqa/selenium/chrome/BUCK index fc7f2e5fd064b..b1a4d810eef10 100644 --- a/java/client/test/org/openqa/selenium/chrome/BUCK +++ b/java/client/test/org/openqa/selenium/chrome/BUCK @@ -20,6 +20,7 @@ java_library(name = 'tests', '//java/client/src/org/openqa/selenium/remote:remote', '//java/client/src/org/openqa/selenium/support/ui:wait', '//java/client/test/org/openqa/selenium/testing:test-base', + '//third_party/java/assertj:assertj', '//third_party/java/gson:gson', '//third_party/java/guava:guava', '//third_party/java/junit:junit', diff --git a/java/client/test/org/openqa/selenium/chrome/ChromeOptionsFunctionalTest.java b/java/client/test/org/openqa/selenium/chrome/ChromeOptionsFunctionalTest.java index b14d921e887a1..934e5723c13d9 100644 --- a/java/client/test/org/openqa/selenium/chrome/ChromeOptionsFunctionalTest.java +++ b/java/client/test/org/openqa/selenium/chrome/ChromeOptionsFunctionalTest.java @@ -17,7 +17,8 @@ package org.openqa.selenium.chrome; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; +import static org.openqa.selenium.remote.CapabilityType.ACCEPT_SSL_CERTS; import static org.openqa.selenium.support.ui.ExpectedConditions.titleIs; import com.google.common.io.Files; @@ -26,7 +27,6 @@ import org.junit.Test; import org.openqa.selenium.By; import org.openqa.selenium.Keys; -import org.openqa.selenium.remote.CapabilityType; import org.openqa.selenium.support.ui.WebDriverWait; import org.openqa.selenium.testing.InProject; import org.openqa.selenium.testing.JUnit4TestBase; @@ -60,7 +60,7 @@ public void canStartChromeWithCustomOptions() { driver.get(pages.clickJacker); Object userAgent = driver.executeScript("return window.navigator.userAgent"); - assertEquals("foo;bar", userAgent); + assertThat(userAgent).isEqualTo("foo;bar"); } @NeedsLocalEnvironment @@ -68,10 +68,9 @@ public void canStartChromeWithCustomOptions() { public void optionsStayEqualAfterSerialization() { ChromeOptions options1 = new ChromeOptions(); ChromeOptions options2 = new ChromeOptions(); - assertEquals("empty chrome options should be equal", options1, options2); + assertThat(options2).isEqualTo(options1); options1.asMap(); - assertEquals("empty chrome options after one is .toJson() should be equal", - options1, options2); + assertThat(options2).isEqualTo(options1); } @NeedsLocalEnvironment @@ -81,7 +80,7 @@ public void canSetAcceptInsecureCerts() { options.setAcceptInsecureCerts(true); driver = new ChromeDriver(options); - assertEquals(driver.getCapabilities().getCapability(CapabilityType.ACCEPT_SSL_CERTS), true); + assertThat(driver.getCapabilities().getCapability(ACCEPT_SSL_CERTS)).isEqualTo(true); } @NeedsLocalEnvironment diff --git a/java/client/test/org/openqa/selenium/firefox/BUCK b/java/client/test/org/openqa/selenium/firefox/BUCK index f4891a958ba5c..ced236dcaeea8 100644 --- a/java/client/test/org/openqa/selenium/firefox/BUCK +++ b/java/client/test/org/openqa/selenium/firefox/BUCK @@ -46,7 +46,7 @@ java_library(name = 'tests', '//java/client/test/org/openqa/selenium/testing/drivers:drivers', '//third_party/java/gson:gson', '//third_party/java/guava:guava', - '//third_party/java/hamcrest:hamcrest-library', + '//third_party/java/assertj:assertj', '//third_party/java/httpcomponents:httpclient', '//third_party/java/junit:junit', '//third_party/java/mockito:mockito-core', diff --git a/java/client/test/org/openqa/selenium/firefox/FirefoxDriverTest.java b/java/client/test/org/openqa/selenium/firefox/FirefoxDriverTest.java index e838bb97ca0a6..b7c2cfd836ae1 100644 --- a/java/client/test/org/openqa/selenium/firefox/FirefoxDriverTest.java +++ b/java/client/test/org/openqa/selenium/firefox/FirefoxDriverTest.java @@ -17,14 +17,7 @@ package org.openqa.selenium.firefox; -import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.greaterThanOrEqualTo; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.lessThan; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.fail; import static org.junit.Assume.assumeNotNull; import static org.mockito.Mockito.any; @@ -34,6 +27,7 @@ import static org.mockito.Mockito.verify; import static org.openqa.selenium.WaitingConditions.elementValueToEqual; import static org.openqa.selenium.remote.CapabilityType.ACCEPT_SSL_CERTS; +import static org.openqa.selenium.remote.CapabilityType.PAGE_LOAD_STRATEGY; import static org.openqa.selenium.support.ui.ExpectedConditions.titleIs; import static org.openqa.selenium.testing.Driver.MARIONETTE; @@ -89,7 +83,7 @@ public void quitDriver() { @Test public void canStartDriverWithNoParameters() { localDriver = new FirefoxDriver(); - assertEquals("firefox", localDriver.getCapabilities().getBrowserName()); + assertThat(localDriver.getCapabilities().getBrowserName()).isEqualTo("firefox"); } @Test @@ -120,9 +114,7 @@ public void canPassCapabilities() { localDriver = new FirefoxDriver(caps); - assertEquals( - "none", - localDriver.getCapabilities().getCapability(CapabilityType.PAGE_LOAD_STRATEGY)); + assertThat(localDriver.getCapabilities().getCapability(PAGE_LOAD_STRATEGY)).isEqualTo("none"); } @Test @@ -213,8 +205,7 @@ public void shouldGetMeaningfulExceptionOnBrowserDeath() throws Exception { driver2.get(pages.formPage); fail("Should have thrown."); } catch (UnreachableBrowserException e) { - assertThat("Must contain descriptive error", e.getMessage(), - containsString("Error communicating with the remote browser")); + assertThat(e.getMessage()).contains("Error communicating with the remote browser"); } finally { keptExecutor.execute(new Command(sessionId, DriverCommand.QUIT)); } @@ -247,8 +238,8 @@ public void shouldBeAbleToStartMoreThanOneInstanceOfTheFirefoxDriverSimultaneous driver.get(pages.xhtmlTestPage); secondDriver.get(pages.formPage); - assertThat(driver.getTitle(), is("XHTML Test Page")); - assertThat(secondDriver.getTitle(), is("We Leave From Here")); + assertThat(driver.getTitle()).isEqualTo("XHTML Test Page"); + assertThat(secondDriver.getTitle()).isEqualTo("We Leave From Here"); } finally { secondDriver.quit(); } @@ -269,7 +260,7 @@ public void aNewProfileShouldAllowSettingAdditionalParameters() { new WebDriverWait(localDriver, 30).until(titleIs("We Leave From Here")); String title = localDriver.getTitle(); - assertThat(title, is("We Leave From Here")); + assertThat(title).isEqualTo("We Leave From Here"); } @Test @@ -281,7 +272,7 @@ public void shouldBeAbleToStartFromProfileWithLogFileSet() throws IOException { profile.setPreference("webdriver.log.file", logFile.getAbsolutePath()); localDriver = new FirefoxDriver(new FirefoxOptions().setProfile(profile)); - assertTrue("log file should exist", logFile.exists()); + assertThat(logFile).exists(); } @Test @@ -316,10 +307,10 @@ public void shouldBeAbleToPassCommandLineOptions() { localDriver = new FirefoxDriver(new FirefoxOptions().setBinary(binary)); Dimension size = localDriver.manage().window().getSize(); - assertThat(size.width, greaterThanOrEqualTo(800)); - assertThat(size.width, lessThan(850)); - assertThat(size.height, greaterThanOrEqualTo(600)); - assertThat(size.height, lessThan(650)); + assertThat(size.width).isGreaterThanOrEqualTo(800); + assertThat(size.width).isLessThan(850); + assertThat(size.height).isGreaterThanOrEqualTo(600); + assertThat(size.height).isLessThan(650); } @@ -330,7 +321,7 @@ public void canBlockInvalidSslCertificates() { localDriver = new FirefoxDriver(new FirefoxOptions().setProfile(profile)); Capabilities caps = localDriver.getCapabilities(); - assertFalse(caps.is(ACCEPT_SSL_CERTS)); + assertThat(caps.is(ACCEPT_SSL_CERTS)).isFalse(); } @Test @@ -351,7 +342,7 @@ private ExpectedCondition urlToBe(final String expectedUrl) { @Ignore(value = MARIONETTE, issue = "https://github.com/mozilla/geckodriver/issues/273") public void canAccessUrlProtectedByBasicAuth() { driver.get(appServer.whereIsWithCredentials("basicAuth", "test", "test")); - assertEquals("authorized", driver.findElement(By.tagName("h1")).getText()); + assertThat(driver.findElement(By.tagName("h1")).getText()).isEqualTo("authorized"); } @Test @@ -377,7 +368,7 @@ public void quit() { } public void assertOnRightPage() { - assertEquals(url, myDriver.getCurrentUrl()); + assertThat(myDriver.getCurrentUrl()).isEqualTo(url); } } @@ -439,7 +430,7 @@ public void multipleFirefoxDriversRunningConcurrently() throws Exception { inputField.clear(); inputField.sendKeys(s); String value = inputField.getAttribute("value"); - assertThat(value, is(s)); + assertThat(value).isEqualTo(s); } }); } @@ -493,8 +484,8 @@ public void canStartFirefoxDriverWithSubclassOfFirefoxProfile() { public void searchingByCssDoesNotPolluteGlobalNamespaceWithSizzleLibrary() { driver.get(pages.xhtmlTestPage); driver.findElement(By.cssSelector("div.content")); - assertEquals(true, - ((JavascriptExecutor) driver).executeScript("return typeof Sizzle == 'undefined';")); + assertThat(((JavascriptExecutor) driver).executeScript("return typeof Sizzle == 'undefined';")) + .isEqualTo(true); } /** @@ -505,8 +496,8 @@ public void searchingByCssDoesNotOverwriteExistingSizzleDefinition() { driver.get(pages.xhtmlTestPage); ((JavascriptExecutor) driver).executeScript("window.Sizzle = 'original sizzle value';"); driver.findElement(By.cssSelector("div.content")); - assertEquals("original sizzle value", - ((JavascriptExecutor) driver).executeScript("return window.Sizzle + '';")); + assertThat(((JavascriptExecutor) driver).executeScript("return window.Sizzle + '';")) + .isEqualTo("original sizzle value"); } @Test @@ -517,8 +508,8 @@ public void testFirefoxCanNativelyClickOverlappingElements() { localDriver = new FirefoxDriver(options); localDriver.get(appServer.whereIs("click_tests/overlapping_elements.html")); localDriver.findElement(By.id("under")).click(); - assertEquals(localDriver.findElement(By.id("log")).getText(), - "Log:\n" + assertThat(localDriver.findElement(By.id("log")).getText()) + .isEqualTo("Log:\n" + "mousedown in over (handled by over)\n" + "mousedown in over (handled by body)\n" + "mouseup in over (handled by over)\n" diff --git a/java/client/test/org/openqa/selenium/firefox/FirefoxOptionsTest.java b/java/client/test/org/openqa/selenium/firefox/FirefoxOptionsTest.java index 555f635d6c7db..b60bd812406d3 100644 --- a/java/client/test/org/openqa/selenium/firefox/FirefoxOptionsTest.java +++ b/java/client/test/org/openqa/selenium/firefox/FirefoxOptionsTest.java @@ -17,26 +17,22 @@ package org.openqa.selenium.firefox; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assumptions.assumeThat; import static java.nio.file.StandardOpenOption.DELETE_ON_CLOSE; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.nullValue; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; -import static org.junit.Assume.assumeNotNull; -import static org.junit.Assume.assumeThat; +import static org.openqa.selenium.PageLoadStrategy.EAGER; +import static org.openqa.selenium.firefox.FirefoxDriver.BINARY; import static org.openqa.selenium.firefox.FirefoxDriver.MARIONETTE; import static org.openqa.selenium.firefox.FirefoxDriver.SystemProperty.BROWSER_BINARY; import static org.openqa.selenium.firefox.FirefoxDriver.SystemProperty.BROWSER_PROFILE; import static org.openqa.selenium.firefox.FirefoxDriver.SystemProperty.DRIVER_USE_MARIONETTE; +import static org.openqa.selenium.firefox.FirefoxDriverLogLevel.DEBUG; +import static org.openqa.selenium.firefox.FirefoxDriverLogLevel.ERROR; +import static org.openqa.selenium.firefox.FirefoxDriverLogLevel.WARN; import static org.openqa.selenium.firefox.FirefoxOptions.FIREFOX_OPTIONS; import static org.openqa.selenium.remote.CapabilityType.ACCEPT_INSECURE_CERTS; import static org.openqa.selenium.remote.CapabilityType.PAGE_LOAD_STRATEGY; -import com.google.common.base.Throwables; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; @@ -69,9 +65,9 @@ public void canInitFirefoxOptionsWithCapabilities() { PAGE_LOAD_STRATEGY, PageLoadStrategy.EAGER, ACCEPT_INSECURE_CERTS, true)); - assertTrue(options.isLegacy()); - assertEquals(options.getCapability(PAGE_LOAD_STRATEGY), PageLoadStrategy.EAGER); - assertEquals(options.getCapability(ACCEPT_INSECURE_CERTS), true); + assertThat(options.isLegacy()).isTrue(); + assertThat(options.getCapability(PAGE_LOAD_STRATEGY)).isEqualTo(EAGER); + assertThat(options.getCapability(ACCEPT_INSECURE_CERTS)).isEqualTo(true); } @Test @@ -82,8 +78,8 @@ public void canInitFirefoxOptionsWithCapabilitiesThatContainFirefoxOptions() { FirefoxOptions options2 = new FirefoxOptions(caps); - assertTrue(options2.isLegacy()); - assertEquals(options2.getCapability(PAGE_LOAD_STRATEGY), PageLoadStrategy.EAGER); + assertThat(options2.isLegacy()).isTrue(); + assertThat(options2.getCapability(PAGE_LOAD_STRATEGY)).isEqualTo(EAGER); } @Test @@ -94,46 +90,42 @@ public void canInitFirefoxOptionsWithCapabilitiesThatContainFirefoxOptionsAsMap( FirefoxOptions options = new FirefoxOptions(caps); - assertSame(options.getProfile(), profile); + assertThat(options.getProfile()).isSameAs(profile); } @Test public void binaryPathNeedNotExist() { - try { - new FirefoxOptions().setBinary("does/not/exist"); - } catch (Exception e) { - fail("Did not expect to see any exceptions thrown: " + e); - } + new FirefoxOptions().setBinary("does/not/exist"); } @Test public void shouldKeepRelativePathToBinaryAsIs() { FirefoxOptions options = new FirefoxOptions().setBinary("some/path"); - assertEquals("some/path", options.getCapability(FirefoxDriver.BINARY)); + assertThat(options.getCapability(BINARY)).isEqualTo("some/path"); } @Test public void shouldConvertPathToBinaryToUseForwardSlashes() { FirefoxOptions options = new FirefoxOptions().setBinary("some\\path"); - assertEquals("some/path", options.getCapability(FirefoxDriver.BINARY)); + assertThat(options.getCapability(BINARY)).isEqualTo("some/path"); } @Test public void shouldKeepWindowsDriveLetterInPathToBinary() { FirefoxOptions options = new FirefoxOptions().setBinary("F:\\some\\path"); - assertEquals("F:/some/path", options.getCapability(FirefoxDriver.BINARY)); + assertThat(options.getCapability(BINARY)).isEqualTo("F:/some/path"); } @Test public void canUseForwardSlashesInWindowsPaths() { FirefoxOptions options = new FirefoxOptions().setBinary("F:\\some\\path"); - assertEquals("F:/some/path", options.getCapability(FirefoxDriver.BINARY)); + assertThat(options.getCapability(BINARY)).isEqualTo("F:/some/path"); } @Test public void shouldKeepWindowsNetworkFileSystemRootInPathToBinary() { FirefoxOptions options = new FirefoxOptions().setBinary("\\\\server\\share\\some\\path"); - assertEquals("//server/share/some/path", options.getCapability(FirefoxDriver.BINARY)); + assertThat(options.getCapability(BINARY)).isEqualTo("//server/share/some/path"); } @Test @@ -142,22 +134,22 @@ public void shouldKeepAFirefoxBinaryAsABinaryIfSetAsOne() throws IOException { fakeExecutable.deleteOnExit(); FirefoxBinary binary = new FirefoxBinary(fakeExecutable); FirefoxOptions options = new FirefoxOptions().setBinary(binary); - assertEquals(binary, options.getCapability(FirefoxDriver.BINARY)); - assertEquals(binary, options.getBinary()); + assertThat(options.getCapability(BINARY)).isEqualTo(binary); + assertThat(options.getBinary()).isEqualTo(binary); } @Test public void stringBasedBinaryRemainsAbsoluteIfSetAsAbsolute() { Map json = new FirefoxOptions().setBinary("/i/like/cheese").asMap(); - assertEquals("/i/like/cheese", ((Map) json.get(FIREFOX_OPTIONS)).get("binary")); + assertThat(((Map) json.get(FIREFOX_OPTIONS)).get("binary")).isEqualTo("/i/like/cheese"); } @Test public void pathBasedBinaryRemainsAbsoluteIfSetAsAbsolute() { Map json = new FirefoxOptions().setBinary(Paths.get("/i/like/cheese")).asMap(); - assertEquals("/i/like/cheese", ((Map) json.get(FIREFOX_OPTIONS)).get("binary")); + assertThat(((Map) json.get(FIREFOX_OPTIONS)).get("binary")).isEqualTo("/i/like/cheese"); } @Test @@ -177,7 +169,7 @@ public void shouldPickUpBinaryFromSystemPropertyIfSet() throws IOException { FirefoxBinary firefoxBinary = options.getBinaryOrNull().orElseThrow(() -> new AssertionError("No binary")); - assertEquals(binary.toString(), firefoxBinary.getPath()); + assertThat(firefoxBinary.getPath()).isEqualTo(binary.toString()); } finally { property.set(resetValue); } @@ -192,15 +184,15 @@ public void shouldPickUpLegacyValueFromSystemProperty() { // No value should default to using Marionette property.set(null); FirefoxOptions options = new FirefoxOptions(); - assertFalse(options.isLegacy()); + assertThat(options.isLegacy()).isFalse(); property.set("false"); options = new FirefoxOptions(); - assertTrue(options.isLegacy()); + assertThat(options.isLegacy()).isTrue(); property.set("true"); options = new FirefoxOptions(); - assertFalse(options.isLegacy()); + assertThat(options.isLegacy()).isFalse(); } finally { property.set(resetValue); } @@ -216,7 +208,7 @@ public void settingMarionetteToFalseAsASystemPropertyDoesNotPrecedence() { property.set("false"); FirefoxOptions options = new FirefoxOptions().merge(caps); - assertFalse(options.isLegacy()); + assertThat(options.isLegacy()).isFalse(); } finally { property.set(resetValue); } @@ -225,7 +217,7 @@ public void settingMarionetteToFalseAsASystemPropertyDoesNotPrecedence() { @Test public void shouldPickUpProfileFromSystemProperty() { FirefoxProfile defaultProfile = new ProfilesIni().getProfile("default"); - assumeNotNull(defaultProfile); + assumeThat(defaultProfile).isNotNull(); JreSystemProperty property = new JreSystemProperty(BROWSER_PROFILE); String resetValue = property.get(); @@ -234,7 +226,7 @@ public void shouldPickUpProfileFromSystemProperty() { FirefoxOptions options = new FirefoxOptions(); FirefoxProfile profile = options.getProfile(); - assertNotNull(profile); + assertThat(profile).isNotNull(); } finally { property.set(resetValue); } @@ -244,7 +236,7 @@ public void shouldPickUpProfileFromSystemProperty() { public void shouldThrowAnExceptionIfSystemPropertyProfileDoesNotExist() { String unlikelyProfileName = "this-profile-does-not-exist-also-cheese"; FirefoxProfile foundProfile = new ProfilesIni().getProfile(unlikelyProfileName); - assumeThat(foundProfile, is(nullValue())); + assumeThat(foundProfile).isNull(); JreSystemProperty property = new JreSystemProperty(BROWSER_PROFILE); String resetValue = property.get(); @@ -260,23 +252,19 @@ public void shouldThrowAnExceptionIfSystemPropertyProfileDoesNotExist() { public void callingToStringWhenTheBinaryDoesNotExistShouldNotCauseAnException() { FirefoxOptions options = new FirefoxOptions().setBinary("there's nothing better in life than cake or peas."); - try { - options.toString(); - // The binary does not exist on this machine, but could do elsewhere. Be chill. - } catch (Exception e) { - fail(Throwables.getStackTraceAsString(e)); - } + options.toString(); + // The binary does not exist on this machine, but could do elsewhere. Be chill. } @Test public void logLevelStringRepresentationIsLowercase() { - assertEquals(FirefoxDriverLogLevel.DEBUG.toString(), "debug"); + assertThat(DEBUG.toString()).isEqualTo("debug"); } @Test public void canBuildLogLevelFromStringRepresentation() { - assertEquals(FirefoxDriverLogLevel.fromString("warn"), FirefoxDriverLogLevel.WARN); - assertEquals(FirefoxDriverLogLevel.fromString("ERROR"), FirefoxDriverLogLevel.ERROR); + assertThat(FirefoxDriverLogLevel.fromString("warn")).isEqualTo(WARN); + assertThat(FirefoxDriverLogLevel.fromString("ERROR")).isEqualTo(ERROR); } @Test @@ -284,8 +272,8 @@ public void canConvertOptionsWithArgsToCapabilitiesAndRestoreBack() { FirefoxOptions options = new FirefoxOptions( new MutableCapabilities(new FirefoxOptions().addArguments("-a", "-b"))); Object options2 = options.asMap().get(FirefoxOptions.FIREFOX_OPTIONS); - assertNotNull(options2); - assertEquals(((Map) options2).get("args"), Arrays.asList("-a", "-b")); + assertThat(options2).isNotNull().isInstanceOf(Map.class); + assertThat(((Map) options2).get("args")).isEqualTo(Arrays.asList("-a", "-b")); } @Test @@ -296,12 +284,12 @@ public void canConvertOptionsWithPrefsToCapabilitiesAndRestoreBack() { .addPreference("int.pref", 42) .addPreference("boolean.pref", true))); Object options2 = options.asMap().get(FirefoxOptions.FIREFOX_OPTIONS); - assertNotNull(options2); + assertThat(options2).isNotNull().isInstanceOf(Map.class); Object prefs = ((Map) options2).get("prefs"); - assertNotNull(prefs); - assertEquals(((Map) prefs).get("string.pref"), "some value"); - assertEquals(((Map) prefs).get("int.pref"), 42); - assertEquals(((Map) prefs).get("boolean.pref"), true); + assertThat(prefs).isNotNull().isInstanceOf(Map.class); + assertThat(((Map) prefs).get("string.pref")).isEqualTo("some value"); + assertThat(((Map) prefs).get("int.pref")).isEqualTo(42); + assertThat(((Map) prefs).get("boolean.pref")).isEqualTo(true); } @Test @@ -309,9 +297,9 @@ public void canConvertOptionsWithBinaryToCapabilitiesAndRestoreBack() { FirefoxOptions options = new FirefoxOptions( new MutableCapabilities(new FirefoxOptions().setBinary(new FirefoxBinary()))); Object options2 = options.asMap().get(FirefoxOptions.FIREFOX_OPTIONS); - assertNotNull(options2); - assertEquals(((Map) options2).get("binary"), - new FirefoxBinary().getPath().replaceAll("\\\\", "/")); + assertThat(options2).isNotNull().isInstanceOf(Map.class); + assertThat(((Map) options2).get("binary")) + .isEqualTo(new FirefoxBinary().getPath().replaceAll("\\\\", "/")); } @Test @@ -324,7 +312,7 @@ public void roundTrippingToCapabilitiesAndBackWorks() { // create a new set of options. This is the round trip, ladies and gentlemen. FirefoxOptions seen = new FirefoxOptions(new ImmutableCapabilities(expected.asMap())); - assertEquals(expected, seen); + assertThat(seen).isEqualTo(expected); } } diff --git a/java/client/test/org/openqa/selenium/firefox/FirefoxProfileTest.java b/java/client/test/org/openqa/selenium/firefox/FirefoxProfileTest.java index 1e27d3529ed7e..f03db34ae35e1 100644 --- a/java/client/test/org/openqa/selenium/firefox/FirefoxProfileTest.java +++ b/java/client/test/org/openqa/selenium/firefox/FirefoxProfileTest.java @@ -17,15 +17,11 @@ package org.openqa.selenium.firefox; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.fail; import org.junit.Before; import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; import org.openqa.selenium.io.FileHandler; import org.openqa.selenium.io.Zip; import org.openqa.selenium.testing.InProject; @@ -45,7 +41,6 @@ import java.util.stream.Collectors; import java.util.stream.Stream; -@RunWith(JUnit4.class) public class FirefoxProfileTest { private static final String FIREBUG_PATH = "third_party/firebug/firebug-1.5.0-fx.xpi"; private static final String FIREBUG_RESOURCE_PATH = @@ -73,7 +68,7 @@ public void getStringPreferenceShouldReturnUserSuppliedValueWhenSet() { profile.setPreference(key, value); String defaultValue = "edam"; - assertEquals(value, profile.getStringPreference(key, defaultValue)); + assertThat(profile.getStringPreference(key, defaultValue)).isEqualTo(value); } @Test @@ -81,7 +76,7 @@ public void getStringPreferenceShouldReturnDefaultValueWhenSet() { String key = "cheese"; String defaultValue = "brie"; - assertEquals(defaultValue, profile.getStringPreference(key, defaultValue)); + assertThat(profile.getStringPreference(key, defaultValue)).isEqualTo(defaultValue); } @Test @@ -98,7 +93,7 @@ public void getIntegerPreferenceShouldReturnUserSuppliedValueWhenSet() { profile.setPreference(key, value); int defaultValue = -42; - assertEquals(1234, profile.getIntegerPreference(key, defaultValue)); + assertThat(profile.getIntegerPreference(key, defaultValue)).isEqualTo(1234); } @Test @@ -106,7 +101,7 @@ public void getIntegerPreferenceShouldReturnDefaultValueWhenSet() { String key = "cheese"; int defaultValue = 42; - assertEquals(defaultValue, profile.getIntegerPreference(key, defaultValue)); + assertThat(profile.getIntegerPreference(key, defaultValue)).isEqualTo(defaultValue); } @Test @@ -123,7 +118,7 @@ public void getBooleanPreferenceShouldReturnUserSuppliedValueWhenSet() { profile.setPreference(key, value); boolean defaultValue = false; - assertEquals(value, profile.getBooleanPreference(key, defaultValue)); + assertThat(profile.getBooleanPreference(key, defaultValue)).isEqualTo(value); } @Test @@ -131,7 +126,7 @@ public void getBooleanPreferenceShouldReturnDefaultValueWhenSet() { String key = "cheese"; boolean defaultValue = true; - assertEquals(defaultValue, profile.getBooleanPreference(key, defaultValue)); + assertThat(profile.getBooleanPreference(key, defaultValue)).isEqualTo(defaultValue); } @Test @@ -157,7 +152,7 @@ public void shouldInstallExtensionFromZip() { profile.addExtension(InProject.locate(FIREBUG_PATH).toFile()); File profileDir = profile.layoutOnDisk(); File extensionDir = new File(profileDir, "extensions/firebug@software.joehewitt.com"); - assertTrue(extensionDir.exists()); + assertThat(extensionDir).exists(); } @Test @@ -165,7 +160,7 @@ public void shouldInstallWebExtensionFromZip() { profile.addExtension(InProject.locate(MOOLTIPASS_PATH).toFile()); File profileDir = profile.layoutOnDisk(); File extensionDir = new File(profileDir, "extensions/MooltipassExtension@1.1.87"); - assertTrue(extensionDir.exists()); + assertThat(extensionDir).exists(); } @Test @@ -175,7 +170,7 @@ public void shouldInstallExtensionFromDirectory() throws IOException { profile.addExtension(unzippedExtension); File profileDir = profile.layoutOnDisk(); File extensionDir = new File(profileDir, "extensions/firebug@software.joehewitt.com"); - assertTrue(extensionDir.exists()); + assertThat(extensionDir).exists(); } @Test @@ -185,7 +180,7 @@ public void shouldInstallWebExtensionFromDirectory() throws IOException { profile.addExtension(unzippedExtension); File profileDir = profile.layoutOnDisk(); File extensionDir = new File(profileDir, "extensions/MooltipassExtension@1.1.87"); - assertTrue(extensionDir.exists()); + assertThat(extensionDir).exists(); } @Test @@ -193,7 +188,7 @@ public void shouldInstallExtensionUsingClasspath() { profile.addExtension(SynthesizedFirefoxDriver.class, FIREBUG_RESOURCE_PATH); File profileDir = profile.layoutOnDisk(); File extensionDir = new File(profileDir, "extensions/firebug@software.joehewitt.com"); - assertTrue(extensionDir.exists()); + assertThat(extensionDir).exists(); } @Test @@ -201,10 +196,10 @@ public void convertingToJsonShouldNotPolluteTempDir() throws IOException { File sysTemp = new File(System.getProperty("java.io.tmpdir")); Set before = Arrays.stream(sysTemp.list()) .filter(f -> f.endsWith("webdriver-profile")).collect(Collectors.toSet()); - assertNotNull(profile.toJson()); + assertThat(profile.toJson()).isNotNull(); Set after = Arrays.stream(sysTemp.list()) .filter(f -> f.endsWith("webdriver-profile")).collect(Collectors.toSet()); - assertEquals(before, after); + assertThat(after).isEqualTo(before); } @Test @@ -213,15 +208,15 @@ public void shouldConvertItselfIntoAMeaningfulRepresentation() throws IOExceptio String json = profile.toJson(); - assertNotNull(json); + assertThat(json).isNotNull(); File dir = Zip.unzipToTempDir(json, "webdriver", "duplicated"); File prefs = new File(dir, "user.js"); - assertTrue(prefs.exists()); + assertThat(prefs.exists()).isTrue(); try (Stream lines = Files.lines(prefs.toPath())) { - assertTrue(lines.anyMatch(s -> s.contains("i.like.cheese"))); + assertThat(lines.anyMatch(s -> s.contains("i.like.cheese"))).isTrue(); } FileHandler.delete(dir); @@ -247,7 +242,8 @@ private List readGeneratedProperties(FirefoxProfile profile) throws Exce public void layoutOnDiskSetsUserPreferences() throws IOException { profile.setPreference("browser.startup.homepage", "http://www.example.com"); Preferences parsedPrefs = parseUserPrefs(profile); - assertEquals("http://www.example.com", parsedPrefs.getPreference("browser.startup.homepage")); + assertThat(parsedPrefs.getPreference("browser.startup.homepage")) + .isEqualTo("http://www.example.com"); } @Test @@ -258,7 +254,8 @@ public void userPrefsArePreservedWhenConvertingToAndFromJson() throws IOExceptio FirefoxProfile rebuilt = FirefoxProfile.fromJson(json); Preferences parsedPrefs = parseUserPrefs(rebuilt); - assertEquals("http://www.example.com", parsedPrefs.getPreference("browser.startup.homepage")); + assertThat(parsedPrefs.getPreference("browser.startup.homepage")) + .isEqualTo("http://www.example.com"); } @Test @@ -270,19 +267,12 @@ public void backslashedCharsArePreservedWhenConvertingToAndFromJson() throws IOE FirefoxProfile rebuilt = FirefoxProfile.fromJson(json); Preferences parsedPrefs = parseUserPrefs(rebuilt); - assertEquals(dir, parsedPrefs.getPreference("browser.download.dir")); + assertThat(parsedPrefs.getPreference("browser.download.dir")).isEqualTo(dir); } private void assertPreferenceValueEquals(String key, Object value) throws Exception { List props = readGeneratedProperties(profile); - boolean seenKey = false; - for (String line : props) { - if (line.contains(key) && line.contains(", " + value + ")")) { - seenKey = true; - } - } - - assertTrue("Did not see value being set correctly", seenKey); + assertThat(props.stream().anyMatch(line -> line.contains(key) && line.contains(", " + value + ")"))).isTrue(); } private Preferences parseUserPrefs(FirefoxProfile profile) throws IOException { diff --git a/java/client/test/org/openqa/selenium/firefox/MarionetteTest.java b/java/client/test/org/openqa/selenium/firefox/MarionetteTest.java index 398c02dc7e903..663ce400b9375 100644 --- a/java/client/test/org/openqa/selenium/firefox/MarionetteTest.java +++ b/java/client/test/org/openqa/selenium/firefox/MarionetteTest.java @@ -17,13 +17,15 @@ package org.openqa.selenium.firefox; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; +import static java.util.Optional.ofNullable; import static org.mockito.Mockito.any; import static org.mockito.Mockito.atLeastOnce; import static org.mockito.Mockito.never; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; +import static org.openqa.selenium.remote.CapabilityType.ACCEPT_INSECURE_CERTS; +import static org.openqa.selenium.remote.CapabilityType.PAGE_LOAD_STRATEGY; import static org.openqa.selenium.testing.Driver.FIREFOX; import org.junit.After; @@ -35,8 +37,6 @@ import org.openqa.selenium.testing.Ignore; import org.openqa.selenium.testing.JUnit4TestBase; -import java.util.Optional; - @Ignore(FIREFOX) public class MarionetteTest extends JUnit4TestBase { @@ -107,8 +107,7 @@ public void canPassCapabilities() { localDriver = new FirefoxDriver(caps); verifyItIsMarionette(localDriver); - assertEquals( - localDriver.getCapabilities().getCapability(CapabilityType.PAGE_LOAD_STRATEGY), "none"); + assertThat(localDriver.getCapabilities().getCapability(PAGE_LOAD_STRATEGY)).isEqualTo("none"); } @Test @@ -188,8 +187,7 @@ public void canPassCapabilitiesBinaryAndProfileSeparately() { verifyItIsMarionette(localDriver); verify(binary, atLeastOnce()).getPath(); verify(binary, never()).startFirefoxProcess(any()); - assertEquals( - localDriver.getCapabilities().getCapability(CapabilityType.PAGE_LOAD_STRATEGY), "none"); + assertThat(localDriver.getCapabilities().getCapability(PAGE_LOAD_STRATEGY)).isEqualTo("none"); } @Test @@ -214,8 +212,7 @@ public void canSetPageLoadStrategyViaOptions() { new FirefoxOptions().setPageLoadStrategy(PageLoadStrategy.NONE)); verifyItIsMarionette(localDriver); - assertEquals(localDriver.getCapabilities() - .getCapability(CapabilityType.PAGE_LOAD_STRATEGY), "none"); + assertThat(localDriver.getCapabilities().getCapability(PAGE_LOAD_STRATEGY)).isEqualTo("none"); } @Test @@ -223,8 +220,7 @@ public void canSetInsecureCertSupportViaOptions() { localDriver = new FirefoxDriver(new FirefoxOptions().setAcceptInsecureCerts(true)); verifyItIsMarionette(localDriver); - assertEquals(localDriver.getCapabilities() - .getCapability(CapabilityType.ACCEPT_INSECURE_CERTS), true); + assertThat(localDriver.getCapabilities().getCapability(ACCEPT_INSECURE_CERTS)).isEqualTo(true); } @Test @@ -232,12 +228,11 @@ public void canStartHeadless() { localDriver = new FirefoxDriver(new FirefoxOptions().setHeadless(true)); verifyItIsMarionette(localDriver); - assertEquals(localDriver.getCapabilities().getCapability("moz:headless"), true); + assertThat(localDriver.getCapabilities().getCapability("moz:headless")).isEqualTo(true); } private void verifyItIsMarionette(FirefoxDriver driver) { - assertNotNull( - Optional.ofNullable(driver.getCapabilities().getCapability("moz:processID")) - .orElse(driver.getCapabilities().getCapability("processId"))); + assertThat(ofNullable(driver.getCapabilities().getCapability("moz:processID")) + .orElse(driver.getCapabilities().getCapability("processId"))).isNotNull(); } } diff --git a/java/client/test/org/openqa/selenium/firefox/PreferencesTest.java b/java/client/test/org/openqa/selenium/firefox/PreferencesTest.java index 5dae5613ff04d..933da28eee09f 100644 --- a/java/client/test/org/openqa/selenium/firefox/PreferencesTest.java +++ b/java/client/test/org/openqa/selenium/firefox/PreferencesTest.java @@ -17,20 +17,15 @@ package org.openqa.selenium.firefox; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import org.junit.Before; import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; import java.io.Reader; import java.io.StringReader; -@RunWith(JUnit4.class) public class PreferencesTest { private static final String emptyDefaults = "{\"mutable\": {}, \"frozen\": {}}"; @@ -43,28 +38,27 @@ public void setUp() { @Test public void stringifyVsStringFormat() { - assertEquals("\"stringifyMe\"", String.format("\"%s\"", "stringifyMe")); + assertThat(String.format("\"%s\"", "stringifyMe")).isEqualTo("\"stringifyMe\""); } @Test public void stringFormatOfStringify() { - assertEquals("\"\"stringifyMe\"\"", String.format("\"%s\"", "\"stringifyMe\"")); + assertThat(String.format("\"%s\"", "\"stringifyMe\"")).isEqualTo("\"\"stringifyMe\"\""); } @Test public void detectStringification() { Preferences a = new Preferences(defaults); - assertFalse("Empty String", canSet(a, "\"\"")); - assertFalse("Valid stringified string", canSet(a, ("\"Julian\""))); - assertTrue("Only start is stringified", canSet(a, ("\"StartOnly"))); - assertTrue("Only end is stringified", canSet(a, ("EndOnly\""))); - assertFalse("Using String.format(\"%%s\")", - canSet(a, (String.format("\"%s\"", "FormatMe")))); - - assertFalse("Stringified string containing extra double-quotes", - canSet(a, ("\"Julian\" \"TestEngineer\" Harty.\""))); + assertThat(canSet(a, "\"\"")).as("Empty String").isFalse(); + assertThat(canSet(a, ("\"Julian\""))).as("Valid stringified string").isFalse(); + assertThat(canSet(a, ("\"StartOnly"))).as("Only start is stringified").isTrue(); + assertThat(canSet(a, ("EndOnly\""))).as("Only end is stringified").isTrue(); + assertThat(canSet(a, (String.format("\"%s\"", "FormatMe")))) + .as("Using String.format(\"%%s\")").isFalse(); + assertThat(canSet(a, ("\"Julian\" \"TestEngineer\" Harty.\""))) + .as("\"Stringified string containing extra double-quotes\"").isFalse(); } @Test @@ -72,7 +66,7 @@ public void parsePreferences_boolean() { StringReader lines = new StringReader("user_pref(\"extensions.update.notifyUser\", false);"); Preferences prefs = new Preferences(defaults, lines); - assertEquals(false, prefs.getPreference("extensions.update.notifyUser")); + assertThat(prefs.getPreference("extensions.update.notifyUser")).isEqualTo(false); } @Test @@ -80,7 +74,7 @@ public void parsePreferences_integer() { StringReader lines = new StringReader("user_pref(\"dom.max_script_run_time\", 34);"); Preferences prefs = new Preferences(defaults, lines); - assertEquals(34, prefs.getPreference("dom.max_script_run_time")); + assertThat(prefs.getPreference("dom.max_script_run_time")).isEqualTo(34); } @Test @@ -94,8 +88,8 @@ public void parsePreferences_string() { "user_pref(\"print.print_command\", \"" + prefWithQuotes + "\");"); Preferences prefs = new Preferences(defaults, lines); - assertEquals(prefWithComma, prefs.getPreference("general.useragent.override")); - assertEquals(prefWithQuotes, prefs.getPreference("print.print_command")); + assertThat(prefs.getPreference("general.useragent.override")).isEqualTo(prefWithComma); + assertThat(prefs.getPreference("print.print_command")).isEqualTo(prefWithQuotes); } @Test @@ -105,8 +99,8 @@ public void parsePreferences_multiline() { "user_pref(\"dom.max_script_run_time\", 32);"); Preferences prefs = new Preferences(defaults, lines); - assertEquals(false, prefs.getPreference("extensions.update.notifyUser")); - assertEquals(32, prefs.getPreference("dom.max_script_run_time")); + assertThat(prefs.getPreference("extensions.update.notifyUser")).isEqualTo(false); + assertThat(prefs.getPreference("dom.max_script_run_time")).isEqualTo(32); } @Test @@ -114,14 +108,9 @@ public void cannotOverrideAFozenPrefence() { StringReader reader = new StringReader("{\"frozen\": {\"frozen.pref\": true }, \"mutable\": {}}"); Preferences preferences = new Preferences(reader); - try { - preferences.setPreference("frozen.pref", false); - fail(); - } catch (IllegalArgumentException expected) { - assertEquals( - "Preference frozen.pref may not be overridden: frozen value=true, requested value=false", - expected.getMessage()); - } + assertThatExceptionOfType(IllegalArgumentException.class) + .isThrownBy(() -> preferences.setPreference("frozen.pref", false)) + .withMessage("Preference frozen.pref may not be overridden: frozen value=true, requested value=false"); } @Test @@ -131,19 +120,16 @@ public void canOverrideAFrozenPreferenceWithTheFrozenValue() { preferences.setPreference("frozen.pref", true); - assertEquals(preferences.getPreference("frozen.pref"), true); + assertThat(preferences.getPreference("frozen.pref")).isEqualTo(true); } @Test public void canOverrideMaxScriptRuntimeIfGreaterThanDefaultValueOrSetToInfinity() { Preferences preferences = new Preferences(defaults); - try { - preferences.setPreference("dom.max_script_run_time", 29); - fail(); - } catch (IllegalArgumentException expected) { - assertEquals("dom.max_script_run_time must be == 0 || >= 30", expected.getMessage()); - } + assertThatExceptionOfType(IllegalArgumentException.class) + .isThrownBy(() -> preferences.setPreference("dom.max_script_run_time", 29)) + .withMessage("dom.max_script_run_time must be == 0 || >= 30"); preferences.setPreference("dom.max_script_run_time", 31); preferences.setPreference("dom.max_script_run_time", 0); diff --git a/java/client/test/org/openqa/selenium/html5/AppCacheTest.java b/java/client/test/org/openqa/selenium/html5/AppCacheTest.java index 3e1712e03a53d..69b210c0cc23d 100644 --- a/java/client/test/org/openqa/selenium/html5/AppCacheTest.java +++ b/java/client/test/org/openqa/selenium/html5/AppCacheTest.java @@ -17,9 +17,10 @@ package org.openqa.selenium.html5; +import static org.assertj.core.api.Assertions.assertThat; import static java.util.concurrent.TimeUnit.MILLISECONDS; -import static org.junit.Assert.assertEquals; import static org.junit.Assume.assumeTrue; +import static org.openqa.selenium.html5.AppCacheStatus.UNCACHED; import org.junit.Before; import org.junit.Test; @@ -41,7 +42,7 @@ public void testAppCacheStatus() { while (status == AppCacheStatus.DOWNLOADING) { status = ((ApplicationCache) driver).getStatus(); } - assertEquals(AppCacheStatus.UNCACHED, status); + assertThat(status).isEqualTo(UNCACHED); } @Test diff --git a/java/client/test/org/openqa/selenium/html5/Html5CapabilitiesTest.java b/java/client/test/org/openqa/selenium/html5/Html5CapabilitiesTest.java index 5afcf5a26483a..04652304f87e2 100644 --- a/java/client/test/org/openqa/selenium/html5/Html5CapabilitiesTest.java +++ b/java/client/test/org/openqa/selenium/html5/Html5CapabilitiesTest.java @@ -17,8 +17,7 @@ package org.openqa.selenium.html5; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assume.assumeTrue; import static org.openqa.selenium.remote.CapabilityType.SUPPORTS_APPLICATION_CACHE; import static org.openqa.selenium.remote.CapabilityType.SUPPORTS_LOCATION_CONTEXT; @@ -60,15 +59,13 @@ public void avoidRemote() { @Test public void enableWebStorageCapability() { configureCapability(SUPPORTS_WEB_STORAGE, true); - assertTrue("Required capability web storage should be enabled", - hasWebStorage(localDriver)); + assertThat(hasWebStorage(localDriver)).isTrue(); } @Test public void disableWebStorageCapability() { configureCapability(SUPPORTS_WEB_STORAGE, false); - assertFalse("Required capability web storage should be disabled", - hasWebStorage(localDriver)); + assertThat(hasWebStorage(localDriver)).isFalse(); } private boolean hasWebStorage(WebDriver driver) { @@ -116,10 +113,8 @@ private void configureCapability(String capability, boolean isEnabled) { Capabilities desiredCaps = new ImmutableCapabilities(capability, isEnabled); localDriver = new WebDriverBuilder().get(desiredCaps); Capabilities caps = ((HasCapabilities) localDriver).getCapabilities(); - assertTrue(String.format("The %s capability should be included in capabilities " + - "for the session", capability), caps.getCapability(capability) != null); - assertTrue(String.format("Capability %s should be set to %b", capability, isEnabled), - caps.is(capability) == isEnabled); + assertThat(caps.getCapability(capability)).isNotNull(); + assertThat(caps.is(capability)).isEqualTo(isEnabled); } @After diff --git a/java/client/test/org/openqa/selenium/html5/LocalStorageTest.java b/java/client/test/org/openqa/selenium/html5/LocalStorageTest.java index ce2a634a39a4f..c99f7f11a6018 100644 --- a/java/client/test/org/openqa/selenium/html5/LocalStorageTest.java +++ b/java/client/test/org/openqa/selenium/html5/LocalStorageTest.java @@ -17,8 +17,7 @@ package org.openqa.selenium.html5; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assume.assumeTrue; import static org.openqa.selenium.testing.Driver.FIREFOX; @@ -45,17 +44,17 @@ public void testLocalStorageSetAndGetItem() { LocalStorage local = ((WebStorage) driver).getLocalStorage(); local.clear(); - assertEquals("Local Storage isn't empty.", 0, local.size()); + assertThat(local.size()).isEqualTo(0); local.setItem("FOO", "BAR"); - assertEquals("BAR", local.getItem("FOO")); + assertThat(local.getItem("FOO")).isEqualTo("BAR"); local.setItem("FOO1", "BAR1"); - assertEquals("BAR1", local.getItem("FOO1")); - assertEquals(2, local.size()); + assertThat(local.getItem("FOO1")).isEqualTo("BAR1"); + assertThat(local.size()).isEqualTo(2); local.clear(); - assertEquals(0, local.size()); + assertThat(local.size()).isEqualTo(0); } @Test @@ -69,13 +68,11 @@ public void testLocalStorageKeySet() { local.setItem("FOO3", "BAR3"); Set keySet = local.keySet(); - assertTrue(keySet.size() == 3); - assertTrue(keySet.contains("FOO1")); - assertTrue(keySet.contains("FOO2")); - assertTrue(keySet.contains("FOO3")); + assertThat(keySet.size()).isEqualTo(3); + assertThat(keySet).contains("FOO1", "FOO2", "FOO3"); local.clear(); - assertTrue(local.keySet().isEmpty()); + assertThat(local.keySet()).isEmpty(); } @Test @@ -84,10 +81,10 @@ public void testClearLocalStorage() { local.setItem("FOO1", "BAR1"); local.setItem("FOO2", "BAR2"); local.setItem("FOO3", "BAR3"); - assertEquals(3, local.size()); + assertThat(local.size()).isEqualTo(3); local.clear(); - assertEquals(0, local.size()); + assertThat(local.size()).isEqualTo(0); } @Test @@ -97,10 +94,10 @@ public void testLocalStorageRemoveItem() { LocalStorage local = ((WebStorage) driver).getLocalStorage(); local.clear(); local.setItem("FOO", "BAR"); - assertEquals(1, local.size()); + assertThat(local.size()).isEqualTo(1); String removedItemValue = local.removeItem("FOO"); - assertEquals("BAR", removedItemValue); - assertEquals(0, local.size()); + assertThat(removedItemValue).isEqualTo("BAR"); + assertThat(local.size()).isEqualTo(0); local.clear(); } @@ -114,18 +111,18 @@ public void testLocalAndSessionStorageDontInterfereWithEachOther() { session.clear(); local.setItem("FOO", "BAR_LOCAL"); session.setItem("FOO", "BAR_SESSION"); - assertEquals(1, local.size()); - assertEquals(1, session.size()); - assertEquals("BAR_LOCAL", local.getItem("FOO")); - assertEquals("BAR_SESSION", session.getItem("FOO")); + assertThat(local.size()).isEqualTo(1); + assertThat(session.size()).isEqualTo(1); + assertThat(local.getItem("FOO")).isEqualTo("BAR_LOCAL"); + assertThat(session.getItem("FOO")).isEqualTo("BAR_SESSION"); String removedItemValue = session.removeItem("FOO"); - assertEquals("BAR_SESSION", removedItemValue); - assertEquals(1, local.size()); - assertEquals(0, session.size()); + assertThat(removedItemValue).isEqualTo("BAR_SESSION"); + assertThat(local.size()).isEqualTo(1); + assertThat(session.size()).isEqualTo(0); removedItemValue = local.removeItem("FOO"); - assertEquals("BAR_LOCAL", removedItemValue); - assertEquals(0, local.size()); - assertEquals(0, session.size()); + assertThat(removedItemValue).isEqualTo("BAR_LOCAL"); + assertThat(local.size()).isEqualTo(0); + assertThat(session.size()).isEqualTo(0); local.clear(); session.clear(); } diff --git a/java/client/test/org/openqa/selenium/html5/LocationContextTest.java b/java/client/test/org/openqa/selenium/html5/LocationContextTest.java index 9f89a8fb1893a..03e965eb27848 100644 --- a/java/client/test/org/openqa/selenium/html5/LocationContextTest.java +++ b/java/client/test/org/openqa/selenium/html5/LocationContextTest.java @@ -17,8 +17,8 @@ package org.openqa.selenium.html5; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.byLessThan; import static org.junit.Assume.assumeTrue; import org.junit.Before; @@ -39,9 +39,9 @@ public void testShouldSetAndGetLocation() { ((LocationContext) driver).setLocation( new Location(40.714353, -74.005973, 0.056747)); Location location = ((LocationContext) driver).location(); - assertNotNull(location); - assertEquals(40.714353, location.getLatitude(), 0.000001); - assertEquals(-74.005973, location.getLongitude(), 0.000001); - assertEquals(0.056747, location.getAltitude(), 0.000001); + assertThat(location).isNotNull(); + assertThat(location.getLatitude()).isCloseTo(40.714353, byLessThan(0.000001)); + assertThat(location.getLongitude()).isCloseTo(-74.005973, byLessThan(0.000001)); + assertThat(location.getAltitude()).isCloseTo(0.056747, byLessThan(0.000001)); } } diff --git a/java/client/test/org/openqa/selenium/html5/SessionStorageTest.java b/java/client/test/org/openqa/selenium/html5/SessionStorageTest.java index 21d5355c5a4d3..aa06a8e0d17fc 100644 --- a/java/client/test/org/openqa/selenium/html5/SessionStorageTest.java +++ b/java/client/test/org/openqa/selenium/html5/SessionStorageTest.java @@ -17,8 +17,7 @@ package org.openqa.selenium.html5; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assume.assumeTrue; import static org.openqa.selenium.testing.Driver.FIREFOX; @@ -40,17 +39,17 @@ public void checkHasWebStorage() { public void testSessionStorageSetAndGetItem() { driver.get(pages.html5Page); SessionStorage session = ((WebStorage) driver).getSessionStorage(); - assertEquals("Session Storage isn't empty.", 0, session.size()); + assertThat(session.size()).isEqualTo(0); session.setItem("BAR", "FOO"); - assertEquals("FOO", session.getItem("BAR")); + assertThat(session.getItem("BAR")).isEqualTo("FOO"); session.setItem("BAR1", "FOO1"); - assertEquals("FOO1", session.getItem("BAR1")); - assertEquals(2, session.size()); + assertThat(session.getItem("BAR1")).isEqualTo("FOO1"); + assertThat(session.size()).isEqualTo(2); session.clear(); - assertEquals(0, session.size()); + assertThat(session.size()).isEqualTo(0); } @Test @@ -64,13 +63,11 @@ public void testSessionStorageKeySet() { session.setItem("FOO3", "BAR3"); Set keySet = session.keySet(); - assertTrue(keySet.size() == 3); - assertTrue(keySet.contains("FOO1")); - assertTrue(keySet.contains("FOO2")); - assertTrue(keySet.contains("FOO3")); + assertThat(keySet).hasSize(3); + assertThat(keySet).contains("FOO1", "FOO2", "FOO3"); session.clear(); - assertTrue(session.keySet().isEmpty()); + assertThat(session.keySet()).isEmpty(); } @Test @@ -79,10 +76,10 @@ public void testClearSessionStorage() { session.setItem("FOO1", "BAR1"); session.setItem("FOO2", "BAR2"); session.setItem("FOO3", "BAR3"); - assertEquals(3, session.size()); + assertThat(session.size()).isEqualTo(3); session.clear(); - assertEquals(0, session.size()); + assertThat(session.size()).isEqualTo(0); } @Test @@ -92,10 +89,10 @@ public void testSessionStorageRemoveItem() { SessionStorage session = ((WebStorage) driver).getSessionStorage(); session.clear(); session.setItem("BAR", "FOO"); - assertEquals(1, session.size()); + assertThat(session.size()).isEqualTo(1); String removedItemValue = session.removeItem("BAR"); - assertEquals("FOO", removedItemValue); - assertEquals(0, session.size()); + assertThat(removedItemValue).isEqualTo("FOO"); + assertThat(session.size()).isEqualTo(0); session.clear(); } } diff --git a/java/client/test/org/openqa/selenium/ie/BUCK b/java/client/test/org/openqa/selenium/ie/BUCK index f9889382198d0..78238bcdc7e2f 100644 --- a/java/client/test/org/openqa/selenium/ie/BUCK +++ b/java/client/test/org/openqa/selenium/ie/BUCK @@ -24,6 +24,7 @@ java_library(name = 'tests', '//java/client/src/org/openqa/selenium/support/ui:wait', '//java/client/test/org/openqa/selenium/testing:test-base', '//java/client/test/org/openqa/selenium/testing/drivers:drivers', + '//third_party/java/assertj:assertj', '//third_party/java/guava:guava', '//third_party/java/junit:junit', ], diff --git a/java/client/test/org/openqa/selenium/ie/InternetExplorerDriverTest.java b/java/client/test/org/openqa/selenium/ie/InternetExplorerDriverTest.java index 44e1eea30a120..c52ab7dfa0220 100644 --- a/java/client/test/org/openqa/selenium/ie/InternetExplorerDriverTest.java +++ b/java/client/test/org/openqa/selenium/ie/InternetExplorerDriverTest.java @@ -17,7 +17,7 @@ package org.openqa.selenium.ie; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assume.assumeTrue; import static org.openqa.selenium.WaitingConditions.elementTextToEqual; import static org.openqa.selenium.ie.InternetExplorerDriver.ENABLE_PERSISTENT_HOVERING; @@ -56,8 +56,8 @@ public void canStartMultipleIeDriverInstances() { try { firstDriver.get(pages.xhtmlTestPage); secondDriver.get(pages.formPage); - assertEquals("XHTML Test Page", firstDriver.getTitle()); - assertEquals("We Leave From Here", secondDriver.getTitle()); + assertThat(firstDriver.getTitle()).isEqualTo("XHTML Test Page"); + assertThat(secondDriver.getTitle()).isEqualTo("We Leave From Here"); } finally { firstDriver.quit(); secondDriver.quit(); @@ -84,7 +84,7 @@ public void testPersistentHoverCanBeTurnedOff() throws Exception { WebElement element = driver.findElement(By.id("menu1")); final WebElement item = driver.findElement(By.id("item1")); - assertEquals("", item.getText()); + assertThat(item.getText()).isEqualTo(""); ((JavascriptExecutor) driver).executeScript("arguments[0].style.background = 'green'", element); new Actions(driver).moveToElement(element).build().perform(); @@ -99,7 +99,7 @@ public void testPersistentHoverCanBeTurnedOff() throws Exception { wait.until(elementTextToEqual(item, "")); - assertEquals("", item.getText()); + assertThat(item.getText()).isEqualTo(""); } finally { driver.quit(); diff --git a/java/client/test/org/openqa/selenium/ie/InternetExplorerOptionsTest.java b/java/client/test/org/openqa/selenium/ie/InternetExplorerOptionsTest.java index b6a9bbbbd177c..ca969b3940f36 100644 --- a/java/client/test/org/openqa/selenium/ie/InternetExplorerOptionsTest.java +++ b/java/client/test/org/openqa/selenium/ie/InternetExplorerOptionsTest.java @@ -17,21 +17,17 @@ package org.openqa.selenium.ie; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.openqa.selenium.ie.InternetExplorerDriver.INITIAL_BROWSER_URL; import static org.openqa.selenium.ie.InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS; import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; import org.openqa.selenium.Capabilities; import org.openqa.selenium.ImmutableCapabilities; import org.openqa.selenium.json.Json; import java.util.Map; -@RunWith(JUnit4.class) public class InternetExplorerOptionsTest { @Test @@ -39,7 +35,7 @@ public void shouldAllowACapabilityToBeSet() { InternetExplorerOptions options = new InternetExplorerOptions(); options.setCapability("cheese", "cake"); - assertEquals(options.toString(), "cake", options.asMap().get("cheese")); + assertThat(options.asMap()).containsEntry("cheese", "cake"); } @Test @@ -48,13 +44,13 @@ public void shouldMirrorCapabilitiesForIeProperly() { InternetExplorerOptions options = new InternetExplorerOptions() .withInitialBrowserUrl(expected); - Map map = options.asMap(); + Map map = options.asMap(); - assertEquals(options.toString(), expected, map.get(INITIAL_BROWSER_URL)); - assertEquals( - options.toString(), - expected, - ((Map) map.get("se:ieOptions")).get(INITIAL_BROWSER_URL)); + assertThat(map).containsEntry(INITIAL_BROWSER_URL, expected); + assertThat(map).containsKey("se:ieOptions"); + assertThat(map.get("se:ieOptions")).isInstanceOf(Map.class); + Map ieOptions = (Map) map.get("se:ieOptions"); + assertThat(ieOptions).containsEntry(INITIAL_BROWSER_URL, expected); } @Test @@ -66,7 +62,7 @@ public void shouldMirrorCapabilitiesFromPassedInIeOptions() { InternetExplorerOptions options = new InternetExplorerOptions(); options.setCapability("se:ieOptions", toMirror); - assertTrue(options.is(INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS)); + assertThat(options.is(INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS)).isTrue(); } @Test @@ -76,14 +72,10 @@ public void shouldPopulateIeOptionsFromExistingCapabilitiesWhichLackThem() { InternetExplorerOptions options = new InternetExplorerOptions(caps); - assertTrue(options.is(INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS)); + assertThat(options.is(INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS)).isTrue(); - Map remoteOptions = (Map) options.getCapability("se:ieOptions"); - - assertEquals( - options.toString(), - true, - remoteOptions.get(INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS)); + Map remoteOptions = (Map) options.getCapability("se:ieOptions"); + assertThat(remoteOptions).containsEntry(INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS, true); } @Test @@ -96,10 +88,10 @@ public void shouldSurviveASerializationRoundTrip() { System.out.println("json = " + json); Capabilities capabilities = new Json().toType(json, Capabilities.class); - assertEquals(options, capabilities); + assertThat(capabilities).isEqualTo(options); InternetExplorerOptions freshOptions = new InternetExplorerOptions(capabilities); - assertEquals(options, freshOptions); + assertThat(freshOptions).isEqualTo(options); } } diff --git a/java/client/test/org/openqa/selenium/interactions/ActionsTest.java b/java/client/test/org/openqa/selenium/interactions/ActionsTest.java index 87a35b3d83376..dc154e3f74e7a 100644 --- a/java/client/test/org/openqa/selenium/interactions/ActionsTest.java +++ b/java/client/test/org/openqa/selenium/interactions/ActionsTest.java @@ -17,17 +17,16 @@ package org.openqa.selenium.interactions; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.when; import static org.mockito.Mockito.withSettings; +import static org.openqa.selenium.Keys.CONTROL; import org.junit.Before; import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; import org.mockito.ArgumentCaptor; import org.mockito.InOrder; import org.mockito.Mock; @@ -45,7 +44,6 @@ /** * Tests the builder for advanced user interaction, the Actions class. */ -@RunWith(JUnit4.class) public class ActionsTest { @Mock private Mouse mockMouse; @@ -156,8 +154,7 @@ public void creatingAllMouseActions() { @Test public void testCtrlClick() { WebDriver driver = mock(WebDriver.class, withSettings().extraInterfaces(Interactive.class)); - ArgumentCaptor> sequenceCaptor = - ArgumentCaptor.forClass((Class) Collection.class); + ArgumentCaptor> sequenceCaptor = ArgumentCaptor.forClass(Collection.class); Mockito.doNothing().when((Interactive) driver).perform(sequenceCaptor.capture()); new Actions(driver) @@ -168,7 +165,7 @@ public void testCtrlClick() { Collection sequence = sequenceCaptor.getValue(); - assertEquals(2, sequence.size()); + assertThat(sequence).hasSize(2); // get mouse and keyboard sequences Map[] sequencesJson = sequence.stream().map(Sequence::toJson).toArray(HashMap[]::new); @@ -182,49 +179,39 @@ public void testCtrlClick() { keyboardSequence = sequencesJson[1]; } - assertEquals("pointer", mouseSequence.get("type")); - List> mouseActions = (List>) mouseSequence.get("actions"); - assertEquals(4, mouseActions.size()); - - assertEquals("key", keyboardSequence.get("type")); - List> keyboardActions = (List>) keyboardSequence.get("actions"); - assertEquals(4, keyboardActions.size()); - - // Mouse pauses as key goes down - Map pauseAction = mouseActions.get(0); - assertEquals("pause", pauseAction.get("type")); - assertEquals(0L, pauseAction.get("duration")); - - Map keyDownAction = keyboardActions.get(0); - assertEquals("keyDown", keyDownAction.get("type")); - assertEquals(Keys.CONTROL.toString(), keyDownAction.get("value")); - - // Mouse goes down, so keyboard pauses - Map pointerDownAction = mouseActions.get(1); - assertEquals("pointerDown", pointerDownAction.get("type")); - assertEquals(0, pointerDownAction.get("button")); - - pauseAction = keyboardActions.get(1); - assertEquals("pause", pauseAction.get("type")); - assertEquals(0L, pauseAction.get("duration")); - - // Mouse goes up, so keyboard pauses - Map pointerUpAction = mouseActions.get(2); - assertEquals("pointerUp", pointerUpAction.get("type")); - assertEquals(0, pointerUpAction.get("button")); - - pauseAction = keyboardActions.get(2); - assertEquals("pause", pauseAction.get("type")); - assertEquals(0L, pauseAction.get("duration")); - - // Mouse pauses as keyboard releases key - pauseAction = mouseActions.get(3); - assertEquals("pause", pauseAction.get("type")); - assertEquals(0L, pauseAction.get("duration")); - - Map keyUpAction = keyboardActions.get(3); - assertEquals("keyUp", keyUpAction.get("type")); - assertEquals(Keys.CONTROL.toString(), keyUpAction.get("value")); + assertThat(mouseSequence).containsEntry("type", "pointer"); + assertThat(mouseSequence.get("actions")).isInstanceOf(List.class); + List> mouseActions = (List>) mouseSequence.get("actions"); + assertThat(mouseActions).hasSize(4); + + assertThat(keyboardSequence).containsEntry("type", "key"); + assertThat(keyboardSequence.get("actions")).isInstanceOf(List.class); + List> keyboardActions = (List>) keyboardSequence.get("actions"); + assertThat(keyboardActions).hasSize(4); + + assertThat(mouseActions.get(0)).as("Mouse pauses as key goes down") + .containsEntry("type", "pause").containsEntry("duration", 0L); + + assertThat(keyboardActions.get(0)).as("Key goes down") + .containsEntry("type", "keyDown").containsEntry("value", CONTROL.toString()); + + assertThat(mouseActions.get(1)).as("Mouse goes down") + .containsEntry("type", "pointerDown").containsEntry("button", 0); + + assertThat(keyboardActions.get(1)).as("Mouse goes down, so keyboard pauses") + .containsEntry("type", "pause").containsEntry("duration", 0L); + + assertThat(mouseActions.get(2)).as("Mouse goes up") + .containsEntry("type", "pointerUp").containsEntry("button", 0); + + assertThat(keyboardActions.get(2)).as("Mouse goes up, so keyboard pauses") + .containsEntry("type", "pause").containsEntry("duration", 0L); + + assertThat(mouseActions.get(3)).as("Mouse pauses as keyboard releases key") + .containsEntry("type", "pause").containsEntry("duration", 0L); + + assertThat(keyboardActions.get(3)).as("Keyboard releases key") + .containsEntry("type", "keyUp").containsEntry("value", CONTROL.toString()); } diff --git a/java/client/test/org/openqa/selenium/interactions/BasicKeyboardInterfaceTest.java b/java/client/test/org/openqa/selenium/interactions/BasicKeyboardInterfaceTest.java index 047d451b68bb0..d0e527e5018fe 100644 --- a/java/client/test/org/openqa/selenium/interactions/BasicKeyboardInterfaceTest.java +++ b/java/client/test/org/openqa/selenium/interactions/BasicKeyboardInterfaceTest.java @@ -17,15 +17,12 @@ package org.openqa.selenium.interactions; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.core.IsInstanceOf.instanceOf; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assume.assumeFalse; import static org.openqa.selenium.testing.Driver.IE; import static org.openqa.selenium.testing.Driver.MARIONETTE; import static org.openqa.selenium.testing.Driver.SAFARI; -import static org.openqa.selenium.testing.TestUtilities.catchThrowable; import org.junit.Test; import org.openqa.selenium.By; @@ -81,8 +78,7 @@ public void testSendingKeyDownOnly() { Action releaseShift = getBuilder(driver).keyUp(keysEventInput, Keys.SHIFT).build(); releaseShift.perform(); - assertTrue("Key down event not isolated, got: " + logText, - logText.endsWith("keydown")); + assertThat(logText).describedAs("Key down event should be isolated").endsWith("keydown"); } @Test @@ -99,15 +95,14 @@ public void testSendingKeyUp() { WebElement keyLoggingElement = driver.findElement(By.id("result")); String eventsText = keyLoggingElement.getText(); - assertTrue("Key down should be isolated for this test to be meaningful. " + - "Got events: " + eventsText, eventsText.endsWith("keydown")); + assertThat(eventsText).describedAs("Key down should be isolated for this test to be meaningful").endsWith("keydown"); Action releaseShift = getBuilder(driver).keyUp(keysEventInput, Keys.SHIFT).build(); releaseShift.perform(); eventsText = keyLoggingElement.getText(); - assertTrue("Key up event not isolated. Got events: " + eventsText, eventsText.endsWith("keyup")); + assertThat(eventsText).describedAs("Key up should be isolated for this test to be meaningful").endsWith("keyup"); } @Test @@ -133,10 +128,9 @@ public void testSendingKeysWithShiftPressed() { releaseShift.perform(); String expectedEvents = " keydown keydown keypress keyup keydown keypress keyup keyup"; - assertThatFormEventsFiredAreExactly("Shift key not held", - existingResult + expectedEvents); + assertThatFormEventsFiredAreExactly("Shift key not held", existingResult + expectedEvents); - assertThat(keysEventInput.getAttribute("value"), is("AB")); + assertThat(keysEventInput.getAttribute("value")).isEqualTo("AB"); } @Test @@ -169,41 +163,36 @@ public void testBasicKeyboardInputOnActiveElement() { @Test public void testThrowsIllegalArgumentExceptionWithNoParameters() { driver.get(pages.javascriptPage); - Throwable t = catchThrowable( - () -> driver.findElement(By.id("keyReporter")).sendKeys()); - assertThat(t, instanceOf(IllegalArgumentException.class)); + assertThatExceptionOfType(IllegalArgumentException.class) + .isThrownBy(() -> driver.findElement(By.id("keyReporter")).sendKeys()); } @Test public void testThrowsIllegalArgumentExceptionWithNullParameter() { driver.get(pages.javascriptPage); - Throwable t = catchThrowable( - () -> driver.findElement(By.id("keyReporter")).sendKeys(null)); - assertThat(t, instanceOf(IllegalArgumentException.class)); + assertThatExceptionOfType(IllegalArgumentException.class) + .isThrownBy(() -> driver.findElement(By.id("keyReporter")).sendKeys(null)); } @Test public void testThrowsIllegalArgumentExceptionWithNullInParameters() { driver.get(pages.javascriptPage); - Throwable t = catchThrowable( - () -> driver.findElement(By.id("keyReporter")).sendKeys("x", null, "y")); - assertThat(t, instanceOf(IllegalArgumentException.class)); + assertThatExceptionOfType(IllegalArgumentException.class) + .isThrownBy(() -> driver.findElement(By.id("keyReporter")).sendKeys("x", null, "y")); } @Test public void testThrowsIllegalArgumentExceptionWithCharSequenceThatContainsNull() { driver.get(pages.javascriptPage); - Throwable t = catchThrowable( - () -> driver.findElement(By.id("keyReporter")).sendKeys(new CharSequence[] {"x", null, "y"})); - assertThat(t, instanceOf(IllegalArgumentException.class)); + assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy( + () -> driver.findElement(By.id("keyReporter")).sendKeys(new CharSequence[]{"x", null, "y"})); } @Test public void testThrowsIllegalArgumentExceptionWithCharSequenceThatContainsNullOnly() { driver.get(pages.javascriptPage); - Throwable t = catchThrowable( - () -> driver.findElement(By.id("keyReporter")).sendKeys(new CharSequence[] {null})); - assertThat(t, instanceOf(IllegalArgumentException.class)); + assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy( + () -> driver.findElement(By.id("keyReporter")).sendKeys(new CharSequence[]{null})); } @Test @@ -247,7 +236,7 @@ public void testSelectionSelectBySymbol() { .sendKeys(Keys.DELETE) .perform(); - assertThat(input.getAttribute("value"), is("abc d")); + assertThat(input.getAttribute("value")).isEqualTo("abc d"); } @Test @@ -263,8 +252,7 @@ public void testSelectionSelectByWord() { WebElement input = driver.findElement(By.id("textInput")); getBuilder(driver).click(input).sendKeys("abc def").perform(); - wait.until( - ExpectedConditions.attributeToBe(input, "value", "abc def")); + wait.until(ExpectedConditions.attributeToBe(input, "value", "abc def")); getBuilder(driver).click(input) .keyDown(Keys.SHIFT) @@ -275,8 +263,7 @@ public void testSelectionSelectByWord() { .sendKeys(Keys.DELETE) .perform(); - wait.until( - ExpectedConditions.attributeToBe(input, "value", "abc ")); + wait.until(ExpectedConditions.attributeToBe(input, "value", "abc ")); } @Test @@ -301,16 +288,16 @@ public void testSelectionSelectAll() { .sendKeys(Keys.DELETE) .perform(); - assertThat(input.getAttribute("value"), is("")); + assertThat(input.getAttribute("value")).isEqualTo(""); } private void assertBackgroundColor(WebElement el, Colors expected) { Color actual = Color.fromString(el.getCssValue("background-color")); - assertThat(actual, is(expected.getColorValue())); + assertThat(actual).isEqualTo(expected.getColorValue()); } private void assertThatFormEventsFiredAreExactly(String message, String expected) { - assertThat(message, getFormEvents(), is(expected.trim())); + assertThat(getFormEvents()).describedAs(message).isEqualTo(expected.trim()); } private String getFormEvents() { @@ -322,6 +309,6 @@ private void assertThatFormEventsFiredAreExactly(String expected) { } private void assertThatBodyEventsFiredAreExactly(String expected) { - assertThat(driver.findElement(By.id("body_result")).getText().trim(), is(expected.trim())); + assertThat(driver.findElement(By.id("body_result")).getText().trim()).isEqualTo(expected.trim()); } } diff --git a/java/client/test/org/openqa/selenium/interactions/BasicMouseInterfaceTest.java b/java/client/test/org/openqa/selenium/interactions/BasicMouseInterfaceTest.java index 057a32f985f89..9af891b869482 100644 --- a/java/client/test/org/openqa/selenium/interactions/BasicMouseInterfaceTest.java +++ b/java/client/test/org/openqa/selenium/interactions/BasicMouseInterfaceTest.java @@ -17,11 +17,12 @@ package org.openqa.selenium.interactions; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.openqa.selenium.WaitingConditions.elementTextToEqual; import static org.openqa.selenium.WaitingConditions.elementValueToEqual; +import static org.openqa.selenium.support.Colors.GREEN; +import static org.openqa.selenium.support.Colors.RED; import static org.openqa.selenium.support.ui.ExpectedConditions.attributeToBe; import static org.openqa.selenium.support.ui.ExpectedConditions.not; import static org.openqa.selenium.support.ui.ExpectedConditions.titleIs; @@ -77,7 +78,7 @@ private void performDragAndDropWithMouse() { Action drop = getBuilder(driver).release(dragInto).build(); - assertEquals("Nothing happened.", dragReporter.getText()); + assertThat(dragReporter.getText()).isEqualTo("Nothing happened."); try { holdItem.perform(); @@ -85,7 +86,7 @@ private void performDragAndDropWithMouse() { moveToOtherList.perform(); String text = dragReporter.getText(); - assertTrue(text, text.matches("Nothing happened. (?:DragOut *)+")); + assertThat(text).matches("Nothing happened. (?:DragOut *)+"); } finally { drop.perform(); } @@ -95,7 +96,7 @@ private void performDragAndDropWithMouse() { public void testDraggingElementWithMouseMovesItToAnotherList() { performDragAndDropWithMouse(); WebElement dragInto = driver.findElement(By.id("sortable1")); - assertEquals(6, dragInto.findElements(By.tagName("li")).size()); + assertThat(dragInto.findElements(By.tagName("li"))).hasSize(6); } // This test is very similar to testDraggingElementWithMouse. The only @@ -107,7 +108,7 @@ public void testDraggingElementWithMouseFiresEvents() { WebElement dragReporter = driver.findElement(By.id("dragging_reports")); // This is failing under HtmlUnit. A bug was filed. String text = dragReporter.getText(); - assertTrue(text, text.matches("Nothing happened. (?:DragOut *)+DropIn RightItem 3")); + assertThat(text).matches("Nothing happened. (?:DragOut *)+DropIn RightItem 3"); } private boolean isElementAvailable(WebDriver driver, By locator) { @@ -164,7 +165,7 @@ public void testDragAndDrop() throws InterruptedException { dropInto = driver.findElement(By.id("droppable")); String text = dropInto.findElement(By.tagName("p")).getText(); - assertEquals("Dropped!", text); + assertThat(text).isEqualTo("Dropped!"); } @Test @@ -177,9 +178,7 @@ public void testDoubleClick() { Action dblClick = getBuilder(driver).doubleClick(toDoubleClick).build(); dblClick.perform(); - String testFieldContent = shortWait.until(elementValueToEqual(toDoubleClick, "DoubleClicked")); - assertEquals("Value should change to DoubleClicked.", "DoubleClicked", - testFieldContent); + shortWait.until(elementValueToEqual(toDoubleClick, "DoubleClicked")); } @Test @@ -191,8 +190,7 @@ public void testContextClick() { Action contextClick = getBuilder(driver).contextClick(toContextClick).build(); contextClick.perform(); - assertEquals("Value should change to ContextClicked.", "ContextClicked", - toContextClick.getAttribute("value")); + assertThat(toContextClick.getAttribute("value")).isEqualTo("ContextClicked"); } @Test @@ -207,23 +205,15 @@ public void testMoveAndClick() { wait.until(elementValueToEqual(toClick, "Clicked")); - assertEquals("Value should change to Clicked.", "Clicked", - toClick.getAttribute("value")); + assertThat(toClick.getAttribute("value")).isEqualTo("Clicked"); } @Test @Ignore(IE) public void testCannotMoveToANullLocator() { driver.get(pages.javascriptPage); - - try { - Action contextClick = getBuilder(driver).moveToElement(null).build(); - - contextClick.perform(); - fail("Shouldn't be allowed to click on null element."); - } catch (IllegalArgumentException expected) { - // Expected. - } + assertThatExceptionOfType(IllegalArgumentException.class) + .isThrownBy(() -> getBuilder(driver).moveToElement(null).build()); } @Test @@ -241,12 +231,8 @@ public void testMousePositionIsNotPreservedInActionsChain() { // TODO(andreastt): Is this correct behaviour? Should the last known mouse position be // disregarded if calling click() from a an Actions chain? - try { - getBuilder(driver).click().build().perform(); - fail("Shouldn't be allowed to click without a context."); - } catch (InvalidCoordinatesException expected) { - // expected - } + assertThatExceptionOfType(InvalidCoordinatesException.class) + .isThrownBy(() -> getBuilder(driver).click().build().perform()); } @Test @@ -322,13 +308,13 @@ public void testShouldAllowUsersToHoverOverElements() { WebElement element = driver.findElement(By.id("menu1")); final WebElement item = driver.findElement(By.id("item1")); - assertEquals("", item.getText()); + assertThat(item.getText()).isEqualTo(""); ((JavascriptExecutor) driver).executeScript("arguments[0].style.background = 'green'", element); new Actions(driver).moveToElement(element).build().perform(); wait.until(not(elementTextToEqual(item, ""))); - assertEquals("Item 1", item.getText()); + assertThat(item.getText()).isEqualTo("Item 1"); } @Test @@ -342,7 +328,7 @@ public void testHoverPersists() throws Exception { WebElement element = driver.findElement(By.id("menu1")); final WebElement item = driver.findElement(By.id("item1")); - assertEquals("", item.getText()); + assertThat(item.getText()).isEqualTo(""); ((JavascriptExecutor) driver).executeScript("arguments[0].style.background = 'green'", element); new Actions(driver).moveToElement(element).build().perform(); @@ -352,7 +338,7 @@ public void testHoverPersists() throws Exception { wait.until(not(elementTextToEqual(item, ""))); - assertEquals("Item 1", item.getText()); + assertThat(item.getText()).isEqualTo("Item 1"); } @Test @@ -460,12 +446,12 @@ public void testCanMoveOverAndOutOfAnElement() { new Actions(driver).moveToElement(greenbox, 1, 1).perform(); - assertEquals( - Colors.GREEN.getColorValue(), Color.fromString(redbox.getCssValue("background-color"))); + assertThat(Color.fromString(redbox.getCssValue("background-color"))) + .isEqualTo(GREEN.getColorValue()); new Actions(driver).moveToElement(redbox).perform(); - assertEquals( - Colors.RED.getColorValue(), Color.fromString(redbox.getCssValue("background-color"))); + assertThat(Color.fromString(redbox.getCssValue("background-color"))) + .isEqualTo(RED.getColorValue()); // IE8 (and *only* IE8) requires a move of 2 pixels. All other browsers // would be happy with 1. diff --git a/java/client/test/org/openqa/selenium/interactions/CombinedInputActionsTest.java b/java/client/test/org/openqa/selenium/interactions/CombinedInputActionsTest.java index 82db1db172aac..ab83aee8120ff 100644 --- a/java/client/test/org/openqa/selenium/interactions/CombinedInputActionsTest.java +++ b/java/client/test/org/openqa/selenium/interactions/CombinedInputActionsTest.java @@ -17,10 +17,7 @@ package org.openqa.selenium.interactions; -import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assume.assumeFalse; import static org.openqa.selenium.WaitingConditions.elementValueToEqual; import static org.openqa.selenium.support.ui.ExpectedConditions.presenceOfElementLocated; @@ -76,8 +73,8 @@ public void testPlainClickingOnMultiSelectionList() { showButton.click(); WebElement resultElement = driver.findElement(By.id("result")); - assertEquals("Should have picked the third option only.", "cheddar", - resultElement.getText()); + assertThat(resultElement.getText()) + .describedAs("Should have picked the third option only").isEqualTo("cheddar"); } @Test @@ -102,8 +99,9 @@ public void testShiftClickingOnMultiSelectionList() { showButton.click(); WebElement resultElement = driver.findElement(By.id("result")); - assertEquals("Should have picked the last three options.", "roquefort parmigiano cheddar", - resultElement.getText()); + assertThat(resultElement.getText()) + .describedAs("Should have picked the last three options") + .isEqualTo("roquefort parmigiano cheddar"); } @Test @@ -129,8 +127,9 @@ public void testControlClickingOnMultiSelectionList() { showButton.click(); WebElement resultElement = driver.findElement(By.id("result")); - assertEquals("Should have picked the first and the third options.", "roquefort cheddar", - resultElement.getText()); + assertThat(resultElement.getText()) + .describedAs("Should have picked the first and the third options") + .isEqualTo("roquefort cheddar"); } @Test @@ -142,7 +141,7 @@ public void testControlClickingOnCustomMultiSelectionList() { WebElement reportingElement = driver.findElement(By.id("infodiv")); - assertEquals("no info", reportingElement.getText()); + assertThat(reportingElement.getText()).isEqualTo("no info"); List listItems = driver.findElements(By.tagName("li")); @@ -156,12 +155,12 @@ public void testControlClickingOnCustomMultiSelectionList() { selectThreeItems.perform(); - assertEquals("#item2 #item4 #item6", reportingElement.getText()); + assertThat(reportingElement.getText()).isEqualTo("#item2 #item4 #item6"); // Now click on another element, make sure that's the only one selected. actions = new Actions(driver); actions.click(listItems.get(6)).build().perform(); - assertEquals("#item7", reportingElement.getText()); + assertThat(reportingElement.getText()).isEqualTo("#item7"); } private void navigateToClicksPageAndClickLink() { @@ -243,7 +242,7 @@ public void testClickAfterMoveToAnElementWithAnOffsetShouldUseLastMousePosition( y = Integer.parseInt(driver.findElement(By.id("pageY")).getText()); } - assertTrue(fuzzyPositionMatching(location.getX() + 20, location.getY() + 10, x, y)); + assertThat(fuzzyPositionMatching(location.getX() + 20, location.getY() + 10, x, y)).isTrue(); } private boolean fuzzyPositionMatching(int expectedX, int expectedY, int actualX, int actualY) { @@ -328,9 +327,10 @@ public void testCombiningShiftAndClickResultsInANewWindow() { .keyUp(Keys.SHIFT) .perform(); - assertEquals("Should have opened a new window.", - nWindows + 1, driver.getWindowHandles().size()); - assertEquals("Should not have navigated away.", originalTitle, driver.getTitle()); + assertThat(driver.getWindowHandles()) + .describedAs("Should have opened a new window").hasSize(nWindows + 1); + assertThat(driver.getTitle()) + .describedAs("Should not have navigated away").isEqualTo(originalTitle); } @Test @@ -342,9 +342,8 @@ public void testHoldingDownShiftKeyWhileClicking() { new Actions(driver).keyDown(Keys.SHIFT).click(toClick).keyUp(Keys.SHIFT).perform(); - WebElement shiftInfo = - wait.until(presenceOfElementLocated(By.id("shiftKey"))); - assertThat(shiftInfo.getText(), equalTo("true")); + WebElement shiftInfo = wait.until(presenceOfElementLocated(By.id("shiftKey"))); + assertThat(shiftInfo.getText()).isEqualTo("true"); } @Test @@ -359,7 +358,7 @@ public void canClickOnASuckerFishStyleMenu() throws InterruptedException { WebElement element = driver.findElement(By.id("menu1")); final WebElement item = driver.findElement(By.id("item1")); - assertEquals("", item.getText()); + assertThat(item.getText()).isEqualTo(""); ((JavascriptExecutor) driver).executeScript("arguments[0].style.background = 'green'", element); new Actions(driver).moveToElement(element).build().perform(); @@ -383,11 +382,11 @@ public void testCanClickOnSuckerFishMenuItem() { WebElement target = driver.findElement(By.id("item1")); - assertTrue(target.isDisplayed()); + assertThat(target.isDisplayed()).isTrue(); target.click(); String text = driver.findElement(By.id("result")).getText(); - assertTrue(text.contains("item 1")); + assertThat(text).contains("item 1"); } } diff --git a/java/client/test/org/openqa/selenium/interactions/CompositeActionTest.java b/java/client/test/org/openqa/selenium/interactions/CompositeActionTest.java index 48b7a68c837a1..09357673ca700 100644 --- a/java/client/test/org/openqa/selenium/interactions/CompositeActionTest.java +++ b/java/client/test/org/openqa/selenium/interactions/CompositeActionTest.java @@ -20,12 +20,9 @@ import static org.mockito.Mockito.mock; import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; import org.mockito.InOrder; import org.mockito.Mockito; -@RunWith(JUnit4.class) public class CompositeActionTest { @Test diff --git a/java/client/test/org/openqa/selenium/interactions/DragAndDropTest.java b/java/client/test/org/openqa/selenium/interactions/DragAndDropTest.java index 5263e7056241f..14775a0b9f4f8 100644 --- a/java/client/test/org/openqa/selenium/interactions/DragAndDropTest.java +++ b/java/client/test/org/openqa/selenium/interactions/DragAndDropTest.java @@ -17,9 +17,7 @@ package org.openqa.selenium.interactions; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.fail; import static org.junit.Assume.assumeFalse; import static org.openqa.selenium.WaitingConditions.elementLocationToBe; @@ -46,9 +44,6 @@ import org.openqa.selenium.testing.TestUtilities; import org.openqa.selenium.testing.drivers.Browser; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - @Ignore(value = HTMLUNIT, reason = "Advanced mouse actions only implemented in rendered browsers") public class DragAndDropTest extends JUnit4TestBase { @@ -77,7 +72,7 @@ public void testDragAndDropToElement() { WebElement img1 = driver.findElement(By.id("test1")); WebElement img2 = driver.findElement(By.id("test2")); new Actions(driver).dragAndDrop(img2, img1).perform(); - assertEquals(img1.getLocation(), img2.getLocation()); + assertThat(img2.getLocation()).isEqualTo(img1.getLocation()); } @SwitchToTopAfterTest @@ -91,7 +86,7 @@ public void testDragAndDropToElementInIframe() { WebElement img1 = wait.until(ExpectedConditions.presenceOfElementLocated(By.id("test1"))); WebElement img2 = driver.findElement(By.id("test2")); new Actions(driver).dragAndDrop(img2, img1).perform(); - assertEquals(img1.getLocation(), img2.getLocation()); + assertThat(img2.getLocation()).isEqualTo(img1.getLocation()); } @SwitchToTopAfterTest @@ -108,7 +103,7 @@ public void testDragAndDropElementWithOffsetInIframeAtBottom() { new Actions(driver).dragAndDropBy(img1, 20, 20).perform(); - assertEquals(initial.moveBy(20, 20), img1.getLocation()); + assertThat(img1.getLocation()).isEqualTo(initial.moveBy(20, 20)); } @NeedsFreshDriver // fails in Sauce if run in a dirty state; to be investigated @@ -124,7 +119,7 @@ public void testDragAndDropElementWithOffsetInScrolledDiv() { new Actions(driver).dragAndDropBy(el, 3700, 3700).perform(); - assertEquals(initial.moveBy(3700, 3700), el.getLocation()); + assertThat(el.getLocation()).isEqualTo(initial.moveBy(3700, 3700)); } @Test @@ -135,7 +130,7 @@ public void testElementInDiv() { WebElement img = driver.findElement(By.id("test3")); Point expectedLocation = img.getLocation(); drag(img, expectedLocation, 100, 100); - assertEquals(expectedLocation, img.getLocation()); + assertThat(img.getLocation()).isEqualTo(expectedLocation); } @Test @@ -176,7 +171,7 @@ public void testShouldAllowUsersToDragAndDropToElementsOffTheCurrentViewPort() { WebElement img = driver.findElement(By.id("test3")); Point expectedLocation = img.getLocation(); drag(img, expectedLocation, 100, 100); - assertEquals(expectedLocation, img.getLocation()); + assertThat(img.getLocation()).isEqualTo(expectedLocation); } private void drag(WebElement elem, Point expectedLocation, @@ -208,17 +203,12 @@ public void testDragAndDropOnJQueryItems() { text = dropInto.findElement(By.tagName("p")).getText(); } - assertEquals("Dropped!", text); + assertThat(text).isEqualTo("Dropped!"); WebElement reporter = driver.findElement(By.id("drop_reports")); // Assert that only one mouse click took place and the mouse was moved // during it. - String reporterText = reporter.getText(); - Pattern pattern = Pattern.compile("start( move)* down( move)+ up( move)*"); - - Matcher matcher = pattern.matcher(reporterText); - - assertTrue("Reporter text:" + reporterText, matcher.matches()); + assertThat(reporter.getText()).matches("start( move)* down( move)+ up( move)*"); } @Test @@ -235,11 +225,11 @@ public void canDragAnElementNotVisibleInTheCurrentViewportDueToAParentOverflow() Point targetLocation = dragTo.getLocation(); int yOffset = targetLocation.getY() - srcLocation.getY(); - assertNotEquals(0, yOffset); + assertThat(yOffset).isNotEqualTo(0); new Actions(driver).dragAndDropBy(toDrag, 0, yOffset).perform(); - assertEquals(dragTo.getLocation(), toDrag.getLocation()); + assertThat(toDrag.getLocation()).isEqualTo(dragTo.getLocation()); } private static void sleep(int ms) { diff --git a/java/client/test/org/openqa/selenium/interactions/IndividualKeyboardActionsTest.java b/java/client/test/org/openqa/selenium/interactions/IndividualKeyboardActionsTest.java index 6285d55efc8c5..51c76e19881ba 100644 --- a/java/client/test/org/openqa/selenium/interactions/IndividualKeyboardActionsTest.java +++ b/java/client/test/org/openqa/selenium/interactions/IndividualKeyboardActionsTest.java @@ -17,14 +17,11 @@ package org.openqa.selenium.interactions; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.mockito.Mockito.when; import org.junit.Before; import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; import org.mockito.InOrder; import org.mockito.Mock; import org.mockito.Mockito; @@ -35,7 +32,6 @@ * Unit test for all simple keyboard actions. * */ -@RunWith(JUnit4.class) public class IndividualKeyboardActionsTest { @Mock private Keyboard mockKeyboard; @@ -130,12 +126,9 @@ public void sendKeysActionOnAnElement() { public void keyDownActionFailsOnNonModifier() { final Keys keyToPress = Keys.BACK_SPACE; - try { - new KeyDownAction(mockKeyboard, mockMouse, stubLocatable, keyToPress); - fail(); - } catch (IllegalArgumentException e) { - assertTrue(e.getMessage().contains("modifier keys")); - } + assertThatExceptionOfType(IllegalArgumentException.class) + .isThrownBy(() -> new KeyDownAction(mockKeyboard, mockMouse, stubLocatable, keyToPress)) + .withMessageContaining("modifier keys"); } @Test diff --git a/java/client/test/org/openqa/selenium/interactions/IndividualMouseActionsTest.java b/java/client/test/org/openqa/selenium/interactions/IndividualMouseActionsTest.java index a8d558404e444..a80b092f2cc22 100644 --- a/java/client/test/org/openqa/selenium/interactions/IndividualMouseActionsTest.java +++ b/java/client/test/org/openqa/selenium/interactions/IndividualMouseActionsTest.java @@ -21,8 +21,6 @@ import org.junit.Before; import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; import org.mockito.InOrder; import org.mockito.Mock; import org.mockito.Mockito; @@ -32,7 +30,6 @@ * Unit test for all simple keyboard actions. * */ -@RunWith(JUnit4.class) public class IndividualMouseActionsTest { @Mock private Mouse mockMouse; diff --git a/java/client/test/org/openqa/selenium/interactions/PointerInputTest.java b/java/client/test/org/openqa/selenium/interactions/PointerInputTest.java index 4c118fc942300..f595d3554fb91 100644 --- a/java/client/test/org/openqa/selenium/interactions/PointerInputTest.java +++ b/java/client/test/org/openqa/selenium/interactions/PointerInputTest.java @@ -17,9 +17,7 @@ package org.openqa.selenium.interactions; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.hasEntry; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import static org.openqa.selenium.remote.Dialect.W3C; import com.google.gson.Gson; @@ -27,8 +25,6 @@ import java.util.List; import java.util.Map; import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; import org.openqa.selenium.WebElement; import org.openqa.selenium.WrappedWebElement; import org.openqa.selenium.interactions.PointerInput.Kind; @@ -39,7 +35,6 @@ /** * Unit test for PointerInputs. */ -@RunWith(JUnit4.class) public class PointerInputTest { @Test @@ -56,9 +51,9 @@ public void encodesWrappedElementInMoveOrigin() { String rawJson = new Json().toJson(sequence); ActionSequenceJson json = new Gson().fromJson(rawJson, ActionSequenceJson.class); - assertEquals(json.actions.size(), 1); + assertThat(json.actions).hasSize(1); ActionJson firstAction = json.actions.get(0); - assertThat(firstAction.origin, hasEntry(W3C.getEncodedElementKey(), "12345")); + assertThat(firstAction.origin).containsEntry(W3C.getEncodedElementKey(), "12345"); } private static class ActionSequenceJson { diff --git a/java/client/test/org/openqa/selenium/interactions/touch/TouchDoubleTapTest.java b/java/client/test/org/openqa/selenium/interactions/touch/TouchDoubleTapTest.java index 80a65c712260f..52a288481a8a1 100644 --- a/java/client/test/org/openqa/selenium/interactions/touch/TouchDoubleTapTest.java +++ b/java/client/test/org/openqa/selenium/interactions/touch/TouchDoubleTapTest.java @@ -17,7 +17,7 @@ package org.openqa.selenium.interactions.touch; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; import org.openqa.selenium.By; @@ -35,12 +35,6 @@ private TouchActions getBuilder(WebDriver driver) { return new TouchActions(driver); } - private void doubleTapOnElement(String elementId) { - WebElement toDoubleTap = driver.findElement(By.id(elementId)); - Action doubleTap = getBuilder(driver).doubleTap(toDoubleTap).build(); - doubleTap.perform(); - } - @Test public void testCanDoubleTapOnAnImageAndAlterLocationOfElementsInScreen() { driver.get(pages.longContentPage); @@ -49,11 +43,13 @@ public void testCanDoubleTapOnAnImageAndAlterLocationOfElementsInScreen() { int y = ((Locatable) image).getCoordinates().inViewPort().y; // The element is located at a certain point, after double tapping, // the y coordinate must change. - assertTrue(y > 100); + assertThat(y).isGreaterThan(100); + + Action doubleTap = getBuilder(driver).doubleTap(image).build(); + doubleTap.perform(); - doubleTapOnElement("imagestart"); y = ((Locatable) image).getCoordinates().inViewPort().y; - assertTrue(y < 50); + assertThat(y).isLessThan(50); } } diff --git a/java/client/test/org/openqa/selenium/interactions/touch/TouchFlickTest.java b/java/client/test/org/openqa/selenium/interactions/touch/TouchFlickTest.java index d281b09ddf435..a1692fbc05bd2 100644 --- a/java/client/test/org/openqa/selenium/interactions/touch/TouchFlickTest.java +++ b/java/client/test/org/openqa/selenium/interactions/touch/TouchFlickTest.java @@ -17,7 +17,7 @@ package org.openqa.selenium.interactions.touch; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; import org.openqa.selenium.By; @@ -44,15 +44,14 @@ public void testCanFlickHorizontallyFromWebElement() { int x = link.getLocation().x; // The element is located at the right of the page, // so it is not initially visible on the screen. - assertTrue("Expected x > 1500, but got x = " + x, x > 1500); + assertThat(x).isGreaterThan(1500); - Action flick = getBuilder(driver).flick(toFlick, -1000, 0, FlickAction.SPEED_NORMAL) - .build(); + Action flick = getBuilder(driver).flick(toFlick, -1000, 0, FlickAction.SPEED_NORMAL).build(); flick.perform(); x = link.getLocation().x; // After flicking, the element should now be visible on the screen. - assertTrue("Expected x < 1500, but got x = " + x, x < 1500); + assertThat(x).isLessThan(1500); } @NeedsFreshDriver @@ -65,14 +64,13 @@ public void testCanFlickHorizontallyFastFromWebElement() { int x = link.getLocation().x; // The element is located at the right of the page, // so it is not initially visible on the screen. - assertTrue(x > 3500); + assertThat(x).isGreaterThan(3500); - Action flick = getBuilder(driver).flick(toFlick, -400, 0, FlickAction.SPEED_FAST) - .build(); + Action flick = getBuilder(driver).flick(toFlick, -400, 0, FlickAction.SPEED_FAST).build(); flick.perform(); x = link.getLocation().x; // After flicking, the element should now be visible on the screen. - assertTrue("Expected x < 3500, but got: " + x, x < 3500); + assertThat(x).isLessThan(3500); } @NeedsFreshDriver @@ -85,13 +83,13 @@ public void testCanFlickHorizontally() { int x = link.getLocation().x; // The element is located at the right of the page, // so it is not initially visible on the screen. - assertTrue("Expected x > 2000, but got x = " + x, x > 1500); + assertThat(x).isGreaterThan(1500); Action flick = getBuilder(driver).flick(1000, 0).build(); flick.perform(); x = link.getLocation().x; // After flicking, the element should now be visible on the screen. - assertTrue("Expected x < 1500, but got x = " + x, x < 1500); + assertThat(x).isLessThan(1500); } @NeedsFreshDriver @@ -103,13 +101,13 @@ public void testCanFlickHorizontallyFast() { int x = link.getLocation().x; // The element is located at the right of the page, // so it is not initially visible on the screen. - assertTrue(x > 3500); + assertThat(x).isGreaterThan(3500); Action flick = getBuilder(driver).flick(1500, 0).build(); flick.perform(); x = link.getLocation().x; // After flicking, the element should now be visible on the screen. - assertTrue("Got: " + x, x < 3000); + assertThat(x).isLessThan(3000); } @NeedsFreshDriver @@ -121,15 +119,14 @@ public void testCanFlickVerticallyFromWebElement() { int y = link.getLocation().y; // The element is located at the bottom of the page, // so it is not initially visible on the screen. - assertTrue(y > 4200); + assertThat(y).isGreaterThan(4200); WebElement toFlick = driver.findElement(By.id("imagestart")); - Action flick = getBuilder(driver).flick(toFlick, 0, -600, FlickAction.SPEED_NORMAL) - .build(); + Action flick = getBuilder(driver).flick(toFlick, 0, -600, FlickAction.SPEED_NORMAL).build(); flick.perform(); y = link.getLocation().y; // After flicking, the element should now be visible on the screen. - assertTrue("Expected y < 4000, but got: " + y, y < 4000); + assertThat(y).isLessThan(4000); } @NeedsFreshDriver @@ -141,15 +138,14 @@ public void testCanFlickVerticallyFastFromWebElement() { int y = link.getLocation().y; // The element is located at the bottom of the page, // so it is not initially visible on the screen. - assertTrue(y > 8700); + assertThat(y).isGreaterThan(8700); WebElement toFlick = driver.findElement(By.id("imagestart")); - Action flick = getBuilder(driver).flick(toFlick, 0, -600, FlickAction.SPEED_FAST) - .build(); + Action flick = getBuilder(driver).flick(toFlick, 0, -600, FlickAction.SPEED_FAST).build(); flick.perform(); y = link.getLocation().y; // After flicking, the element should now be visible on the screen. - assertTrue("Expected y < 8700, but got: " + y, y < 8700); + assertThat(y).isLessThan(8700); } @NeedsFreshDriver @@ -161,14 +157,14 @@ public void testCanFlickVertically() { int y = link.getLocation().y; // The element is located at the bottom of the page, // so it is not initially visible on the screen. - assertTrue(y > 4200); + assertThat(y).isGreaterThan(4200); Action flick = getBuilder(driver).flick(0, 750).build(); flick.perform(); y = link.getLocation().y; // After flicking, the element should now be visible on the screen. - assertTrue("Got: " + y, y < 4200); + assertThat(y).isLessThan(4200); } @NeedsFreshDriver @@ -180,12 +176,12 @@ public void testCanFlickVerticallyFast() { int y = link.getLocation().y; // The element is located at the bottom of the page, // so it is not initially visible on the screen. - assertTrue(y > 8700); + assertThat(y).isGreaterThan(8700); Action flick = getBuilder(driver).flick(0, 1500).build(); flick.perform(); y = link.getLocation().y; // After flicking, the element should now be visible on the screen. - assertTrue("Got: " + y, y < 4000); + assertThat(y).isLessThan(4000); } } diff --git a/java/client/test/org/openqa/selenium/interactions/touch/TouchLongPressTest.java b/java/client/test/org/openqa/selenium/interactions/touch/TouchLongPressTest.java index aa03ca94bcfd4..ac9c3d8a03891 100644 --- a/java/client/test/org/openqa/selenium/interactions/touch/TouchLongPressTest.java +++ b/java/client/test/org/openqa/selenium/interactions/touch/TouchLongPressTest.java @@ -24,8 +24,6 @@ import org.junit.Before; import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.openqa.selenium.interactions.Locatable; @@ -35,7 +33,6 @@ /** * Tests the long press action. */ -@RunWith(JUnit4.class) public class TouchLongPressTest { @Mock private TouchScreen mockTouch; diff --git a/java/client/test/org/openqa/selenium/interactions/touch/TouchScrollTest.java b/java/client/test/org/openqa/selenium/interactions/touch/TouchScrollTest.java index b294b914e56b2..645ba34a283bb 100644 --- a/java/client/test/org/openqa/selenium/interactions/touch/TouchScrollTest.java +++ b/java/client/test/org/openqa/selenium/interactions/touch/TouchScrollTest.java @@ -17,7 +17,7 @@ package org.openqa.selenium.interactions.touch; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; import org.openqa.selenium.By; @@ -43,7 +43,7 @@ public void testCanScrollVerticallyFromWebElement() { int y = link.getLocation().y; // The element is located at the right of the page, // so it is not initially visible on the screen. - assertTrue("Expected y > 4200, but got y = " + y, y > 4200); + assertThat(y).isGreaterThan(4200); WebElement toScroll = driver.findElement(By.id("imagestart")); Action scroll = getBuilder(driver).scroll(toScroll, 0, -800).build(); @@ -51,7 +51,7 @@ public void testCanScrollVerticallyFromWebElement() { y = link.getLocation().y; // After scrolling, the location of the element should change accordingly. - assertTrue("Expected y < 3500, but got y = " + y, y < 3500); + assertThat(y).isLessThan(3500); } @NeedsFreshDriver @@ -63,7 +63,7 @@ public void testCanScrollHorizontallyFromWebElement() { int x = link.getLocation().x; // The element is located at the right of the page, // so it is not initially visible on the screen. - assertTrue("Expected x > 1500, but got x = " + x, x > 1500); + assertThat(x).isGreaterThan(1500); WebElement toScroll = driver.findElement(By.id("imagestart")); Action scroll = getBuilder(driver).scroll(toScroll, -1000, 0).build(); @@ -71,7 +71,7 @@ public void testCanScrollHorizontallyFromWebElement() { x = link.getLocation().x; // After scrolling, the location of the element should change accordingly. - assertTrue("Expected x < 1500, but got x = " + x, x < 1500); + assertThat(x).isLessThan(1500); } @NeedsFreshDriver @@ -83,14 +83,14 @@ public void testCanScrollVertically() { int y = link.getLocation().y; // The element is located at the right of the page, // so it is not initially visible on the screen. - assertTrue(y > 4200); + assertThat(y).isGreaterThan(4200); Action scrollDown = getBuilder(driver).scroll(0, 800).build(); scrollDown.perform(); y = link.getLocation().y; // After scrolling, the location of the element should change accordingly. - assertTrue(y < 3500); + assertThat(y).isLessThan(3500); } @NeedsFreshDriver @@ -102,13 +102,13 @@ public void testCanScrollHorizontally() { int x = link.getLocation().x; // The element is located at the right of the page, // so it is not initially visible on the screen. - assertTrue("Expected x > 1500, but got x = " + x, x > 1500); + assertThat(x).isGreaterThan(1500); Action scrollDown = getBuilder(driver).scroll(400, 0).build(); scrollDown.perform(); x = link.getLocation().y; // After scrolling, the location of the element should change accordingly. - assertTrue("Expected x < 1500, but got x = " + x, x < 1500); + assertThat(x).isLessThan(1500); } } diff --git a/java/client/test/org/openqa/selenium/interactions/touch/TouchSingleTapTest.java b/java/client/test/org/openqa/selenium/interactions/touch/TouchSingleTapTest.java index 701fa26dcc021..1b4356b91eeb6 100644 --- a/java/client/test/org/openqa/selenium/interactions/touch/TouchSingleTapTest.java +++ b/java/client/test/org/openqa/selenium/interactions/touch/TouchSingleTapTest.java @@ -17,7 +17,7 @@ package org.openqa.selenium.interactions.touch; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.openqa.selenium.support.ui.ExpectedConditions.titleIs; import org.junit.Test; @@ -57,6 +57,6 @@ public void testCanSingleTapOnAnAnchorAndNotReloadThePage() { Boolean samePage = (Boolean) ((JavascriptExecutor) driver) .executeScript("return document.latch"); - assertTrue(samePage); + assertThat(samePage).isTrue(); } } diff --git a/java/client/test/org/openqa/selenium/interactions/touch/TouchTestBase.java b/java/client/test/org/openqa/selenium/interactions/touch/TouchTestBase.java index c119616249e4e..2e025b8c57393 100644 --- a/java/client/test/org/openqa/selenium/interactions/touch/TouchTestBase.java +++ b/java/client/test/org/openqa/selenium/interactions/touch/TouchTestBase.java @@ -17,8 +17,7 @@ package org.openqa.selenium.interactions.touch; -import static org.hamcrest.Matchers.instanceOf; -import static org.junit.Assume.assumeThat; +import static org.assertj.core.api.Assumptions.assumeThat; import org.junit.Before; import org.openqa.selenium.interactions.HasTouchScreen; @@ -27,6 +26,6 @@ public abstract class TouchTestBase extends JUnit4TestBase { @Before public void checkHasTouchScreen() { - assumeThat(driver, instanceOf(HasTouchScreen.class)); + assumeThat(driver).isInstanceOf(HasTouchScreen.class); } } diff --git a/java/client/test/org/openqa/selenium/io/FileHandlerTest.java b/java/client/test/org/openqa/selenium/io/FileHandlerTest.java index e434c4c129c49..147eb81331d06 100644 --- a/java/client/test/org/openqa/selenium/io/FileHandlerTest.java +++ b/java/client/test/org/openqa/selenium/io/FileHandlerTest.java @@ -17,12 +17,9 @@ package org.openqa.selenium.io; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; import java.io.File; import java.io.FileOutputStream; @@ -30,21 +27,20 @@ import java.io.OutputStream; import java.util.Random; -@RunWith(JUnit4.class) public class FileHandlerTest { @Test public void testFileCopy() throws IOException { File newFile = File.createTempFile("testFileCopy", "dst"); File tmpFile = writeTestFile(File.createTempFile("FileUtilTest", "src")); - assertTrue(newFile.length() == 0); - assertTrue(tmpFile.length() > 0); + assertThat(newFile.length()).isEqualTo(0); + assertThat(tmpFile.length()).isGreaterThan(0); try { // Copy it. FileHandler.copy(tmpFile, newFile); - assertEquals(tmpFile.length(), newFile.length()); + assertThat(newFile.length()).isEqualTo(tmpFile.length()); } finally { tmpFile.delete(); newFile.delete(); diff --git a/java/client/test/org/openqa/selenium/io/TemporaryFilesystemTest.java b/java/client/test/org/openqa/selenium/io/TemporaryFilesystemTest.java index 4fe8545bdd424..358878e12f609 100644 --- a/java/client/test/org/openqa/selenium/io/TemporaryFilesystemTest.java +++ b/java/client/test/org/openqa/selenium/io/TemporaryFilesystemTest.java @@ -17,19 +17,16 @@ package org.openqa.selenium.io; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; +import org.junit.Assume; import org.junit.Before; import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; import org.openqa.selenium.WebDriverException; import java.io.File; import java.io.IOException; -@RunWith(JUnit4.class) public class TemporaryFilesystemTest { private TemporaryFilesystem tmpFs; @@ -45,7 +42,7 @@ public void setUp() { public void testCanCreateTempFiles() { File tmp = tmpFs.createTempDir("TemporaryFilesystem", "canCreate"); try { - assertTrue(tmp.exists()); + assertThat(tmp).exists(); } catch (WebDriverException e) { tmp.delete(); throw e; @@ -54,77 +51,57 @@ public void testCanCreateTempFiles() { @Test public void testFilesystemCleanupDeletesDirs() { - if (!tmpFs.shouldReap()) { - System.out.println("Reaping of files disabled - " + - "ignoring testFilesystemCleanupDeletesDirs"); - return; - } + Assume.assumeTrue("Reaping of files disabled", tmpFs.shouldReap()); + File tmp = tmpFs.createTempDir("TemporaryFilesystem", "fcdd"); - assertTrue(tmp.exists()); + assertThat(tmp).exists(); tmpFs.deleteTemporaryFiles(); - assertFalse(tmp.exists()); + assertThat(tmp).doesNotExist(); } @Test public void testFilesystemCleanupDeletesRecursive() throws IOException { - if (!tmpFs.shouldReap()) { - System.out.println("Reaping of files disabled - " + - "ignoring testFilesystemCleanupDeletesRecursive"); - return; - } + Assume.assumeTrue("Reaping of files disabled", tmpFs.shouldReap()); + File tmp = tmpFs.createTempDir("TemporaryFilesystem", "fcdr"); createDummyFilesystemContent(tmp); tmpFs.deleteTemporaryFiles(); - assertFalse(tmp.exists()); + assertThat(tmp).doesNotExist(); } @Test public void testSpecificDeleteRequestHonored() throws IOException { - if (!tmpFs.shouldReap()) { - System.out.println("Reaping of files disabled - " + - "ignoring testSpecificDeleteRequestHonored"); - return; - } + Assume.assumeTrue("Reaping of files disabled", tmpFs.shouldReap()); + File tmp = tmpFs.createTempDir("TemporaryFilesystem", "sdrh"); createDummyFilesystemContent(tmp); tmpFs.deleteTempDir(tmp); - assertFalse(tmp.exists()); + assertThat(tmp).doesNotExist(); } @Test public void testDoesNotDeleteArbitraryFiles() throws IOException { File tempFile = File.createTempFile("TemporaryFilesystem", "dndaf"); - assertTrue(tempFile.exists()); + assertThat(tempFile).exists(); try { tmpFs.deleteTempDir(tempFile); - assertTrue(tempFile.exists()); + assertThat(tempFile).exists(); } finally { tempFile.delete(); } } - @Test - public void testShouldReapDefaultsTrue() { - if (!tmpFs.shouldReap()) { - System.out.println("Reaping of files disabled - " + - "ignoring testShouldReapDefaultsTrue"); - return; - } - - assertTrue(tmpFs.shouldReap()); - } - @Test public void testShouldDeleteTempDir() { final File tempDir = tmpFs.createTempDir("foo", "bar"); - assertTrue(tempDir.exists()); + assertThat(tempDir).exists(); tmpFs.deleteTemporaryFiles(); tmpFs.deleteBaseDir(); - assertFalse(tempDir.exists()); + assertThat(tempDir).doesNotExist(); } @Test @@ -154,11 +131,11 @@ public void testShouldBeAbleToModifyDefaultInstance() throws IOException { // Reset to the default dir TemporaryFilesystem.setTemporaryDirectory(new File(System.getProperty("java.io.tmpdir"))); - assertTrue("Directory should have been created in the provided temp dir.", isInOtherDir); + assertThat(isInOtherDir).isTrue(); } private void createDummyFilesystemContent(File dir) throws IOException { - assertTrue(dir.isDirectory()); + assertThat(dir.isDirectory()).isTrue(); File.createTempFile("cleanup", "file", dir); File childDir = new File(dir, "child"); childDir.mkdir(); diff --git a/java/client/test/org/openqa/selenium/io/ZipTest.java b/java/client/test/org/openqa/selenium/io/ZipTest.java index d9e86c0dfcc67..119dbacb4ba81 100644 --- a/java/client/test/org/openqa/selenium/io/ZipTest.java +++ b/java/client/test/org/openqa/selenium/io/ZipTest.java @@ -17,15 +17,11 @@ package org.openqa.selenium.io; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import org.junit.After; import org.junit.Before; import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; import java.io.File; import java.io.FileInputStream; @@ -36,7 +32,6 @@ import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; -@RunWith(JUnit4.class) public class ZipTest { private File inputDir; private File outputDir; @@ -70,8 +65,8 @@ public void testCanZipASingleFile() throws IOException { File unzipped = new File(outputDir, "foo.txt"); File notThere = new File(outputDir, "nay.txt"); - assertTrue(unzipped.exists()); - assertFalse(notThere.exists()); + assertThat(unzipped).exists(); + assertThat(notThere).doesNotExist(); } @Test @@ -87,8 +82,8 @@ public void testCanZipADirectory() throws IOException { File unzipped1 = new File(outputDir, "foo.txt"); File unzipped2 = new File(outputDir, "bar/bar.txt"); - assertTrue(unzipped1.exists()); - assertTrue(unzipped2.exists()); + assertThat(unzipped1).exists(); + assertThat(unzipped2).exists(); } @Test @@ -96,7 +91,7 @@ public void testCanUnzip() throws IOException { File testZip = File.createTempFile("testUnzip", "zip"); writeTestZip(testZip, 25); File out = Zip.unzipToTempDir(new FileInputStream(testZip), "unzip", "stream"); - assertEquals(25, out.list().length); + assertThat(out.list()).hasSize(25); } private File writeTestZip(File file, int files) throws IOException { @@ -126,7 +121,7 @@ private void writeTestZipEntry(ZipOutputStream out) throws IOException { private void writeTestFile(File file) throws IOException { File parent = file.getParentFile(); if (!parent.exists()) { - assertTrue(parent.mkdirs()); + assertThat(parent.mkdirs()).isTrue(); } byte[] byteArray = new byte[16384]; new Random().nextBytes(byteArray); diff --git a/java/client/test/org/openqa/selenium/javascript/BUCK b/java/client/test/org/openqa/selenium/javascript/BUCK index 573d0df63ad1b..d17fc6ef5f200 100644 --- a/java/client/test/org/openqa/selenium/javascript/BUCK +++ b/java/client/test/org/openqa/selenium/javascript/BUCK @@ -6,7 +6,7 @@ java_library(name = 'javascript', '//java/client/test/org/openqa/selenium/testing:test-base', '//java/client/test/org/openqa/selenium/testing/drivers:drivers', '//third_party/java/guava:guava', - '//third_party/java/hamcrest:hamcrest-library', + '//third_party/java/assertj:assertj', '//third_party/java/junit:junit', ], visibility = [ diff --git a/java/client/test/org/openqa/selenium/json/BUCK b/java/client/test/org/openqa/selenium/json/BUCK index b2dc4ef2c7ca0..72ea0b820e017 100644 --- a/java/client/test/org/openqa/selenium/json/BUCK +++ b/java/client/test/org/openqa/selenium/json/BUCK @@ -8,7 +8,7 @@ java_test(name = 'small-tests', '//java/client/src/org/openqa/selenium/remote:remote', '//third_party/java/gson:gson', '//third_party/java/guava:guava', - '//third_party/java/hamcrest:hamcrest-library', + '//third_party/java/assertj:assertj', '//third_party/java/junit:junit', ], ) diff --git a/java/client/test/org/openqa/selenium/json/JsonInputTest.java b/java/client/test/org/openqa/selenium/json/JsonInputTest.java index 5e0939d650e96..0d286ecc92580 100644 --- a/java/client/test/org/openqa/selenium/json/JsonInputTest.java +++ b/java/client/test/org/openqa/selenium/json/JsonInputTest.java @@ -17,11 +17,17 @@ package org.openqa.selenium.json; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.openqa.selenium.json.Json.MAP_TYPE; +import static org.openqa.selenium.json.JsonType.BOOLEAN; +import static org.openqa.selenium.json.JsonType.END_COLLECTION; +import static org.openqa.selenium.json.JsonType.END_MAP; +import static org.openqa.selenium.json.JsonType.NAME; +import static org.openqa.selenium.json.JsonType.NULL; +import static org.openqa.selenium.json.JsonType.NUMBER; +import static org.openqa.selenium.json.JsonType.START_COLLECTION; +import static org.openqa.selenium.json.JsonType.START_MAP; +import static org.openqa.selenium.json.JsonType.STRING; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; @@ -37,56 +43,56 @@ public class JsonInputTest { @Test public void shouldParseBooleanValues() { JsonInput input = newInput(true); - assertEquals(JsonType.BOOLEAN, input.peek()); - assertTrue(input.nextBoolean()); + assertThat(input.peek()).isEqualTo(BOOLEAN); + assertThat(input.nextBoolean()).isTrue(); input = newInput(false); - assertEquals(JsonType.BOOLEAN, input.peek()); - assertFalse(input.nextBoolean()); + assertThat(input.peek()).isEqualTo(BOOLEAN); + assertThat(input.nextBoolean()).isFalse(); } @Test public void shouldParseNonDecimalNumbersAsLongs() { JsonInput input = newInput(42); - assertEquals(JsonType.NUMBER, input.peek()); - assertEquals(42L, input.nextNumber()); + assertThat(input.peek()).isEqualTo(NUMBER); + assertThat(input.nextNumber()).isEqualTo(42L); } @Test public void shouldParseDecimalNumbersAsDoubles() { JsonInput input = newInput(42.0); - assertEquals(JsonType.NUMBER, input.peek()); - assertEquals(42.0d, (Double) input.nextNumber(), 0); + assertThat(input.peek()).isEqualTo(NUMBER); + assertThat((Double) input.nextNumber()).isEqualTo(42.0d); } @Test public void shouldHandleNullValues() { JsonInput input = newInput(null); - assertEquals(JsonType.NULL, input.peek()); - assertNull(input.nextNull()); + assertThat(input.peek()).isEqualTo(NULL); + assertThat(input.nextNull()).isNull(); } @Test public void shouldBeAbleToReadAString() { JsonInput input = newInput("cheese"); - assertEquals(JsonType.STRING, input.peek()); - assertEquals("cheese", input.nextString()); + assertThat(input.peek()).isEqualTo(STRING); + assertThat(input.nextString()).isEqualTo("cheese"); } @Test public void shouldBeAbleToReadTheEmptyString() { JsonInput input = newInput(""); - assertEquals(JsonType.STRING, input.peek()); - assertEquals("", input.nextString()); + assertThat(input.peek()).isEqualTo(STRING); + assertThat(input.nextString()).isEqualTo(""); } @Test public void anEmptyArrayHasNoContents() { JsonInput input = newInput(ImmutableList.of()); - assertEquals(JsonType.START_COLLECTION, input.peek()); + assertThat(input.peek()).isEqualTo(START_COLLECTION); input.beginArray(); - assertFalse(input.hasNext()); - assertEquals(JsonType.END_COLLECTION, input.peek()); + assertThat(input.hasNext()).isFalse(); + assertThat(input.peek()).isEqualTo(END_COLLECTION); input.endArray(); } @@ -94,7 +100,7 @@ public void anEmptyArrayHasNoContents() { public void anArrayWithASingleElementHasNextButOnlyOneValue() { JsonInput input = newInput(ImmutableList.of("peas")); input.beginArray(); - assertEquals("peas", input.nextString()); + assertThat(input.nextString()).isEqualTo("peas"); input.endArray(); } @@ -102,11 +108,11 @@ public void anArrayWithASingleElementHasNextButOnlyOneValue() { public void anArrayWithMultipleElementsReturnsTrueFromHasNextMoreThanOnce() { JsonInput input = newInput(ImmutableList.of("brie", "cheddar")); input.beginArray(); - assertTrue(input.hasNext()); - assertEquals("brie", input.nextString()); - assertTrue(input.hasNext()); - assertEquals("cheddar", input.nextString()); - assertFalse(input.hasNext()); + assertThat(input.hasNext()).isTrue(); + assertThat(input.nextString()).isEqualTo("brie"); + assertThat(input.hasNext()).isTrue(); + assertThat(input.nextString()).isEqualTo("cheddar"); + assertThat(input.hasNext()).isFalse(); input.endArray(); } @@ -119,10 +125,10 @@ public void callingHasNextWhenNotInAnArrayOrMapIsAnError() { @Test public void anEmptyMapHasNoContents() { JsonInput input = newInput(ImmutableMap.of()); - assertEquals(JsonType.START_MAP, input.peek()); + assertThat(input.peek()).isEqualTo(START_MAP); input.beginObject(); - assertFalse(input.hasNext()); - assertEquals(JsonType.END_MAP, input.peek()); + assertThat(input.hasNext()).isFalse(); + assertThat(input.peek()).isEqualTo(END_MAP); input.endObject(); } @@ -130,12 +136,12 @@ public void anEmptyMapHasNoContents() { public void canReadAMapWithASingleEntry() { JsonInput input = newInput(ImmutableMap.of("cheese", "feta")); input.beginObject(); - assertTrue(input.hasNext()); - assertEquals(JsonType.NAME, input.peek()); - assertEquals("cheese", input.nextName()); - assertEquals(JsonType.STRING, input.peek()); - assertEquals("feta", input.nextString()); - assertFalse(input.hasNext()); + assertThat(input.hasNext()).isTrue(); + assertThat(input.peek()).isEqualTo(NAME); + assertThat(input.nextName()).isEqualTo("cheese"); + assertThat(input.peek()).isEqualTo(STRING); + assertThat(input.nextString()).isEqualTo("feta"); + assertThat(input.hasNext()).isFalse(); input.endObject(); } @@ -146,22 +152,22 @@ public void canReadAMapWithManyEntries() { "vegetable", "peas", "random", 42)); - assertEquals(JsonType.START_MAP, input.peek()); + assertThat(input.peek()).isEqualTo(START_MAP); input.beginObject(); - assertTrue(input.hasNext()); - assertEquals(JsonType.NAME, input.peek()); - assertEquals("cheese", input.nextName()); - assertEquals("stilton", input.nextString()); - assertTrue(input.hasNext()); - assertEquals(JsonType.NAME, input.peek()); - assertEquals("vegetable", input.nextName()); - assertEquals("peas", input.nextString()); - assertTrue(input.hasNext()); - assertEquals(JsonType.NAME, input.peek()); - assertEquals("random", input.nextName()); - assertEquals(42L, input.nextNumber()); - assertFalse(input.hasNext()); - assertEquals(JsonType.END_MAP, input.peek()); + assertThat(input.hasNext()).isTrue(); + assertThat(input.peek()).isEqualTo(NAME); + assertThat(input.nextName()).isEqualTo("cheese"); + assertThat(input.nextString()).isEqualTo("stilton"); + assertThat(input.hasNext()).isTrue(); + assertThat(input.peek()).isEqualTo(NAME); + assertThat(input.nextName()).isEqualTo("vegetable"); + assertThat(input.nextString()).isEqualTo("peas"); + assertThat(input.hasNext()).isTrue(); + assertThat(input.peek()).isEqualTo(NAME); + assertThat(input.nextName()).isEqualTo("random"); + assertThat(input.nextNumber()).isEqualTo(42L); + assertThat(input.hasNext()).isFalse(); + assertThat(input.peek()).isEqualTo(END_MAP); input.endObject(); } @@ -171,21 +177,21 @@ public void nestedMapIsFine() { "map", ImmutableMap.of("child", ImmutableList.of("hello", "world")))); input.beginObject(); - assertTrue(input.hasNext()); - assertEquals("map", input.nextName()); + assertThat(input.hasNext()).isTrue(); + assertThat(input.nextName()).isEqualTo("map"); input.beginObject(); - assertTrue(input.hasNext()); - assertEquals("child", input.nextName()); + assertThat(input.hasNext()).isTrue(); + assertThat(input.nextName()).isEqualTo("child"); input.beginArray(); - assertTrue(input.hasNext()); - assertEquals("hello", input.nextString()); - assertTrue(input.hasNext()); - assertEquals("world", input.nextString()); - assertFalse(input.hasNext()); + assertThat(input.hasNext()).isTrue(); + assertThat(input.nextString()).isEqualTo("hello"); + assertThat(input.hasNext()).isTrue(); + assertThat(input.nextString()).isEqualTo("world"); + assertThat(input.hasNext()).isFalse(); input.endArray(); - assertFalse(input.hasNext()); + assertThat(input.hasNext()).isFalse(); input.endObject(); - assertFalse(input.hasNext()); + assertThat(input.hasNext()).isFalse(); input.endObject(); } @@ -196,7 +202,7 @@ public void shouldDecodeUnicodeEscapesProperly() { try (JsonInput in = new JsonInput(new StringReader(raw), new JsonTypeCoercer())) { Map map = in.read(MAP_TYPE); - assertEquals(" line = (Map) stack.get(0); Object o = line.get("lineNumber"); - assertTrue("line number is of type: " + o.getClass(), o instanceof Long); + assertThat(o).isInstanceOf(Long.class); } @Test public void testShouldNotChokeWhenCollectionIsNull() { - try { - convert(new BeanWithNullCollection()); - } catch (Exception e) { - e.printStackTrace(); - fail("That shouldn't have happened"); - } + convert(new BeanWithNullCollection()); } @Test @@ -181,18 +171,12 @@ public void testNullAndAnEmptyStringAreEncodedDifferently() { String nullValue = convert(null); String emptyString = convert(""); - assertNotEquals(emptyString, nullValue); + assertThat(emptyString).isNotEqualTo(nullValue); } @Test public void testShouldBeAbleToConvertAPoint() { - Point point = new Point(65, 75); - - try { - convert(point); - } catch (StackOverflowError e) { - fail("This should never happen"); - } + convert(new Point(65, 75)); } @Test @@ -201,7 +185,7 @@ public void testShouldEncodeClassNameAsClassProperty() { JsonObject converted = new JsonParser().parse(json).getAsJsonObject(); - assertEquals(SimpleBean.class.getName(), converted.get("class").getAsString()); + assertThat(converted.get("class").getAsString()).isEqualTo(SimpleBean.class.getName()); } @Test @@ -211,7 +195,7 @@ public void testShouldBeAbleToConvertASessionId() { JsonObject converted = new JsonParser().parse(json).getAsJsonObject(); - assertEquals("some id", converted.get("value").getAsString()); + assertThat(converted.get("value").getAsString()).isEqualTo("some id"); } @Test @@ -222,7 +206,7 @@ public void testShouldBeAbleToConvertAJsonObject() { JsonObject converted = new JsonParser().parse(json).getAsJsonObject(); - assertEquals("value", converted.get("key").getAsString()); + assertThat(converted.get("key").getAsString()).isEqualTo("value"); } @Test @@ -233,7 +217,7 @@ public void testShouldBeAbleToConvertACapabilityObject() { JsonObject converted = new JsonParser().parse(json).getAsJsonObject(); - assertEquals("alpha", converted.get("key").getAsString()); + assertThat(converted.get("key").getAsString()).isEqualTo("alpha"); } @Test @@ -251,21 +235,20 @@ public void testShouldConvertAProxyCorrectly() { JsonObject converted = new JsonParser().parse(json).getAsJsonObject(); JsonObject capsAsMap = converted.get("desiredCapabilities").getAsJsonObject(); - assertEquals(json, proxy.getHttpProxy(), - capsAsMap.get(CapabilityType.PROXY).getAsJsonObject() - .get("httpProxy").getAsString()); + assertThat(capsAsMap.get(CapabilityType.PROXY).getAsJsonObject().get("httpProxy").getAsString()) + .isEqualTo(proxy.getHttpProxy()); } @Test public void testShouldCallToJsonMethodIfPresent() { String json = convert(new JsonAware("converted")); - assertEquals("\"converted\"", json); + assertThat(json).isEqualTo("\"converted\""); } @Test public void testShouldPreferToJsonMethodToToMapMethod() { String json = convert(new MappableJsonAware("converted")); - assertEquals("\"converted\"", json); + assertThat(json).isEqualTo("\"converted\""); } @Test @@ -280,8 +263,8 @@ public Map toJson() { String json = convert(new ToJsonReturnsMap()); JsonObject converted = new JsonParser().parse(json).getAsJsonObject(); - assertEquals(1, converted.entrySet().size()); - assertEquals("peas", converted.get("cheese").getAsString()); + assertThat(converted.entrySet()).hasSize(1); + assertThat(converted.get("cheese").getAsString()).isEqualTo("peas"); } @Test @@ -296,11 +279,11 @@ public Set toJson() { String json = convert(new ToJsonReturnsCollection()); JsonArray converted = new JsonParser().parse(json).getAsJsonArray(); - assertEquals(2, converted.size()); + assertThat(converted).hasSize(2); JsonArray expected = new JsonArray(); expected.add(new JsonPrimitive("cheese")); expected.add(new JsonPrimitive("peas")); - assertEquals(expected, converted); + assertThat(converted).isEqualTo(expected); } @Test @@ -309,7 +292,7 @@ public void testShouldCallAsMapMethodIfPresent() { Map value = new Json().toType(json, MAP_TYPE); - assertEquals(ImmutableMap.of("a key", "a value"), value); + assertThat(value).isEqualTo(ImmutableMap.of("a key", "a value")); } @Test @@ -318,7 +301,7 @@ public void testShouldCallToMapMethodIfPresent() { Map value = new Json().toType(json, MAP_TYPE); - assertEquals(ImmutableMap.of("a key", "a value"), value); + assertThat(value).isEqualTo(ImmutableMap.of("a key", "a value")); } @Test @@ -327,23 +310,20 @@ public void testConvertsToJsonMethodResultToPrimitiveIfItIsNotJson() { // as malformed because of the slash. String raw = "gnu/linux"; - try { - // Make sure that the parser does actually reject this so the test is - // meaningful. If this stops failing, choose a different malformed JSON - // string. - new JsonParser().parse(raw).toString(); - fail("Expected a parser exception when parsing: " + raw); - } catch (JsonSyntaxException expected) { - } + // Make sure that the parser does actually reject this so the test is + // meaningful. If this stops failing, choose a different malformed JSON + // string. + assertThatExceptionOfType(JsonSyntaxException.class) + .isThrownBy(() -> new JsonParser().parse(raw).toString()); String json = convert(new JsonAware(raw)); // The JSON spec says that we should encode the forward stroke ("solidus"). Decode the string - assertTrue(json.startsWith("\"")); - assertTrue(json.endsWith("\"")); + assertThat(json.startsWith("\"")).isTrue(); + assertThat(json.endsWith("\"")).isTrue(); json = new JsonParser().parse(json).getAsString(); - assertEquals("gnu/linux", json); + assertThat(json).isEqualTo("gnu/linux"); } private void verifyStackTraceInJson(String json, StackTraceElement[] stackTrace) { @@ -351,20 +331,17 @@ private void verifyStackTraceInJson(String json, StackTraceElement[] stackTrace) for (StackTraceElement e : stackTrace) { if (e.getFileName() != null) { // Native methods may have null filenames - assertTrue("Filename not found", json.contains("\"fileName\": \"" + e.getFileName() + "\"")); + assertThat(json).contains("\"fileName\": \"" + e.getFileName() + "\""); } - assertTrue("Line number not found", - json.contains("\"lineNumber\": " + e.getLineNumber() + "")); - assertTrue("class not found.", - json.contains("\"class\": \"" + e.getClass().getName() + "\"")); - assertTrue("class name not found", - json.contains("\"className\": \"" + e.getClassName() + "\"")); - assertTrue("method name not found.", - json.contains("\"methodName\": \"" + e.getMethodName() + "\"")); + assertThat(json) + .contains("\"lineNumber\": " + e.getLineNumber() + "", + "\"class\": \"" + e.getClass().getName() + "\"", + "\"className\": \"" + e.getClassName() + "\"", + "\"methodName\": \"" + e.getMethodName() + "\""); int posOfCurrStackTraceElement = json.indexOf(e.getMethodName()); - assertTrue("Mismatch in order of stack trace elements.", - posOfCurrStackTraceElement > posOfLastStackTraceElement); + assertThat(posOfCurrStackTraceElement).isGreaterThan(posOfLastStackTraceElement) + .describedAs("Mismatch in order of stack trace elements"); } } @@ -373,9 +350,9 @@ public void testShouldBeAbleToConvertARuntimeException() { RuntimeException clientError = new RuntimeException("foo bar baz!"); StackTraceElement[] stackTrace = clientError.getStackTrace(); String json = convert(clientError); - assertTrue(json.contains("\"message\": \"foo bar baz!\"")); - assertTrue(json.contains("\"class\": \"java.lang.RuntimeException\"")); - assertTrue(json.contains("\"stackTrace\"")); + assertThat(json).contains("\"message\": \"foo bar baz!\"", + "\"class\": \"java.lang.RuntimeException\"", + "\"stackTrace\""); verifyStackTraceInJson(json, stackTrace); } @@ -387,32 +364,31 @@ public void testShouldBeAbleToConvertAWebDriverException() { JsonObject converted = new JsonParser().parse(raw).getAsJsonObject(); - assertTrue(raw, converted.has("buildInformation")); - assertTrue(raw, converted.has("systemInformation")); - assertTrue(raw, converted.has("additionalInformation")); + assertThat(converted.has("buildInformation")).isTrue(); + assertThat(converted.has("systemInformation")).isTrue(); + assertThat(converted.has("additionalInformation")).isTrue(); - assertTrue(raw, converted.has("message")); - assertThat(converted.get("message").getAsString(), containsString("foo bar baz!")); - assertThat(converted.get("class").getAsString(), is(WebDriverException.class.getName())); + assertThat(converted.has("message")).isTrue(); + assertThat(converted.get("message").getAsString()).contains("foo bar baz!"); + assertThat(converted.get("class").getAsString()).isEqualTo(WebDriverException.class.getName()); - assertTrue(raw, converted.has("stackTrace")); + assertThat(converted.has("stackTrace")).isTrue(); verifyStackTraceInJson(raw, stackTrace); } @Test public void testShouldConvertUnhandledAlertException() { RuntimeException clientError = new UnhandledAlertException("unhandled alert", "cheese!"); - Map obj = new Gson() - .fromJson(new StringReader(convert(clientError)), Map.class); - assertTrue(obj.containsKey("alert")); - assertEquals(ImmutableMap.of("text", "cheese!"), obj.get("alert")); + Map obj = new Gson().fromJson(new StringReader(convert(clientError)), Map.class); + assertThat(obj).containsKey("alert"); + assertThat(obj.get("alert")).isEqualTo(ImmutableMap.of("text", "cheese!")); } @Test public void testShouldConvertDatesToMillisecondsInUtcTime() { String jsonStr = convert(new Date(0)); - assertEquals(0, Integer.valueOf(jsonStr).intValue()); + assertThat(valueOf(jsonStr).intValue()).isEqualTo(0); } @Test @@ -436,8 +412,8 @@ public Date getDate() { JsonObject converted = new JsonParser().parse(jsonStr).getAsJsonObject(); - assertTrue(converted.has("date")); - assertEquals(123456L, converted.get("date").getAsLong()); + assertThat(converted.has("date")).isTrue(); + assertThat(converted.get("date").getAsLong()).isEqualTo(123456L); } @Test @@ -449,23 +425,21 @@ public void testShouldBeAbleToConvertACookie() { JsonObject converted = new JsonParser().parse(jsonStr).getAsJsonObject(); - assertEquals("name", converted.get("name").getAsString()); - assertEquals("value", converted.get("value").getAsString()); - assertEquals("domain", converted.get("domain").getAsString()); - assertEquals("/path", converted.get("path").getAsString()); - assertTrue(converted.get("secure").getAsBoolean()); - assertTrue(converted.get("httpOnly").getAsBoolean()); - assertEquals(TimeUnit.MILLISECONDS.toSeconds(expiry.getTime()), - converted.get("expiry").getAsLong()); + assertThat(converted.get("name").getAsString()).isEqualTo("name"); + assertThat(converted.get("value").getAsString()).isEqualTo("value"); + assertThat(converted.get("domain").getAsString()).isEqualTo("domain"); + assertThat(converted.get("path").getAsString()).isEqualTo("/path"); + assertThat(converted.get("secure").getAsBoolean()).isTrue(); + assertThat(converted.get("httpOnly").getAsBoolean()).isTrue(); + assertThat(converted.get("expiry").getAsLong()) + .isEqualTo(MILLISECONDS.toSeconds(expiry.getTime())); } @Test public void testUnsetCookieFieldsAreUndefined() { Cookie cookie = new Cookie("name", "value"); String jsonStr = convert(cookie); - // assertThat(jsonStr, not(containsString("path"))); - assertThat(jsonStr, not(containsString("domain"))); - assertThat(jsonStr, not(containsString("expiry"))); + assertThat(jsonStr).doesNotContain("domain", "expiry"); } @Test @@ -475,8 +449,8 @@ public void testProperlyConvertsNulls() { String payload = convert(frameId); Map result = new Json().toType(payload, MAP_TYPE); - assertTrue(result.containsKey("id")); - assertNull(result.get("id")); + assertThat(result).containsKey("id"); + assertThat(result.get("id")).isNull(); } @Test @@ -491,10 +465,10 @@ public void testConvertLoggingPreferencesToJson() { JsonObject converted = new JsonParser().parse(json).getAsJsonObject(); - assertEquals("WARNING", converted.get(LogType.BROWSER).getAsString()); - assertEquals("DEBUG", converted.get(LogType.CLIENT).getAsString()); - assertEquals("ALL", converted.get(LogType.DRIVER).getAsString()); - assertEquals("OFF", converted.get(LogType.SERVER).getAsString()); + assertThat(converted.get(BROWSER).getAsString()).isEqualTo("WARNING"); + assertThat(converted.get(CLIENT).getAsString()).isEqualTo("DEBUG"); + assertThat(converted.get(DRIVER).getAsString()).isEqualTo("ALL"); + assertThat(converted.get(SERVER).getAsString()).isEqualTo("OFF"); } @Test @@ -503,9 +477,9 @@ public void testConvertsLogEntryToJson() { JsonObject converted = new JsonParser().parse(raw).getAsJsonObject(); - assertEquals("foo", converted.get("message").getAsString()); - assertEquals(17, converted.get("timestamp").getAsLong()); - assertEquals("OFF", converted.get("level").getAsString()); + assertThat(converted.get("message").getAsString()).isEqualTo("foo"); + assertThat(converted.get("timestamp").getAsLong()).isEqualTo(17); + assertThat(converted.get("level").getAsString()).isEqualTo("OFF"); } @Test @@ -521,12 +495,12 @@ public void testConvertLogEntriesToJson() { JsonObject obj1 = converted.get(0).getAsJsonObject(); JsonObject obj2 = converted.get(1).getAsJsonObject(); - assertEquals("OFF", obj1.get("level").getAsString()); - assertEquals(timestamp, obj1.get("timestamp").getAsLong()); - assertEquals("entry1", obj1.get("message").getAsString()); - assertEquals("WARNING", obj2.get("level").getAsString()); - assertEquals(timestamp, obj2.get("timestamp").getAsLong()); - assertEquals("entry2", obj2.get("message").getAsString()); + assertThat(obj1.get("level").getAsString()).isEqualTo("OFF"); + assertThat(obj1.get("timestamp").getAsLong()).isEqualTo(timestamp); + assertThat(obj1.get("message").getAsString()).isEqualTo("entry1"); + assertThat(obj2.get("level").getAsString()).isEqualTo("WARNING"); + assertThat(obj2.get("timestamp").getAsLong()).isEqualTo(timestamp); + assertThat(obj2.get("message").getAsString()).isEqualTo("entry2"); } @Test @@ -542,17 +516,17 @@ public void testShouldBeAbleToConvertACommand() { JsonObject converted = new JsonParser().parse(json).getAsJsonObject(); - assertTrue(converted.has("sessionId")); + assertThat(converted.has("sessionId")).isTrue(); JsonObject sid = converted.get("sessionId").getAsJsonObject(); - assertEquals(sid.get("value").getAsString(), sessionId.toString()); + assertThat(sid.get("value").getAsString()).isEqualTo(sessionId.toString()); - assertEquals(converted.get("name").getAsString(), commandName); + assertThat(commandName).isEqualTo(converted.get("name").getAsString()); - assertTrue(converted.has("parameters")); + assertThat(converted.has("parameters")).isTrue(); JsonObject pars = converted.get("parameters").getAsJsonObject(); - assertEquals(pars.entrySet().size(), 2); - assertEquals(pars.get("param1").getAsString(), parameters.get("param1")); - assertEquals(pars.get("param2").getAsString(), parameters.get("param2")); + assertThat(pars.entrySet()).hasSize(2); + assertThat(pars.get("param1").getAsString()).isEqualTo(parameters.get("param1")); + assertThat(pars.get("param2").getAsString()).isEqualTo(parameters.get("param2")); } @Test @@ -563,7 +537,7 @@ public void shouldConvertAUrlToAString() throws MalformedURLException { String seen = new Json().toJson(toConvert); JsonObject converted = new JsonParser().parse(seen).getAsJsonObject(); - assertEquals(url.toExternalForm(), converted.get("url").getAsString()); + assertThat(converted.get("url").getAsString()).isEqualTo(url.toExternalForm()); } @Test @@ -575,7 +549,7 @@ public void shouldNotIncludePropertiesFromJavaLangObjectOtherThanClass() { Stream.of(SimplePropertyDescriptor.getPropertyDescriptors(Object.class)) .filter(pd -> !"class".equals(pd.getName())) .map(SimplePropertyDescriptor::getName) - .forEach(name -> assertFalse(name, converted.keySet().contains(name))); + .forEach(name -> assertThat(converted.keySet()).contains(name)); } @Test @@ -589,9 +563,8 @@ public void shouldAllowValuesToBeStreamedToACollection() { .endArray(); } - assertEquals( - ImmutableList.of("brie", "peas"), - new Json().toType(builder.toString(), Object.class)); + assertThat((Object) new Json().toType(builder.toString(), Object.class)) + .isEqualTo(ImmutableList.of("brie", "peas")); } @Test @@ -605,9 +578,8 @@ public void shouldAllowValuesToBeStreamedToAnObject() { .endObject(); } - assertEquals( - ImmutableMap.of("cheese", "brie", "vegetable", "peas"), - new Json().toType(builder.toString(), MAP_TYPE)); + assertThat((Object) new Json().toType(builder.toString(), MAP_TYPE)) + .isEqualTo(ImmutableMap.of("cheese", "brie", "vegetable", "peas")); } @Test @@ -616,8 +588,9 @@ public void whenConvertingObjectsContainingClassesDoNotBeNoisy() { JsonObject converted = new JsonParser().parse(json).getAsJsonObject(); - assertEquals(1, converted.size()); - assertEquals(SimpleBean.class.getName(), converted.getAsJsonPrimitive("thing").getAsString()); + assertThat(converted.size()).isEqualTo(1); + assertThat(converted.getAsJsonPrimitive("thing").getAsString()) + .isEqualTo(SimpleBean.class.getName()); } @Test @@ -634,14 +607,14 @@ public void canDisablePrettyPrintingToGetSingleLineOutput() { out.write(toEncode); } - assertEquals(-1, json.indexOf("\n")); + assertThat(json.indexOf("\n")).isEqualTo(-1); } @Test public void shouldEncodeLogLevelsAsStrings() { String converted = convert(Level.INFO); - assertEquals("\"INFO\"", converted); + assertThat(converted).isEqualTo("\"INFO\""); } private String convert(Object toConvert) { diff --git a/java/client/test/org/openqa/selenium/json/JsonTest.java b/java/client/test/org/openqa/selenium/json/JsonTest.java index c2dfad041d6b5..f60fd38d9520c 100644 --- a/java/client/test/org/openqa/selenium/json/JsonTest.java +++ b/java/client/test/org/openqa/selenium/json/JsonTest.java @@ -17,18 +17,18 @@ package org.openqa.selenium.json; -import static org.hamcrest.Matchers.hasEntry; -import static org.hamcrest.Matchers.instanceOf; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.core.IsEqual.equalTo; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static java.util.logging.Level.ALL; +import static java.util.logging.Level.FINE; +import static java.util.logging.Level.OFF; +import static java.util.logging.Level.WARNING; +import static org.assertj.core.api.Assertions.byLessThan; +import static org.openqa.selenium.Proxy.ProxyType.PAC; import static org.openqa.selenium.json.Json.MAP_TYPE; +import static org.openqa.selenium.logging.LogType.BROWSER; +import static org.openqa.selenium.logging.LogType.CLIENT; +import static org.openqa.selenium.logging.LogType.DRIVER; +import static org.openqa.selenium.logging.LogType.SERVER; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; @@ -43,7 +43,6 @@ import org.openqa.selenium.MutableCapabilities; import org.openqa.selenium.Platform; import org.openqa.selenium.Proxy; -import org.openqa.selenium.logging.LogType; import org.openqa.selenium.logging.LoggingPreferences; import org.openqa.selenium.remote.CapabilityType; import org.openqa.selenium.remote.Command; @@ -59,21 +58,20 @@ import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; -import java.util.logging.Level; public class JsonTest { @Test public void canReadBooleans() { - assertTrue(new Json().toType("true", Boolean.class)); - assertFalse(new Json().toType("false", Boolean.class)); + assertThat((Boolean) new Json().toType("true", Boolean.class)).isTrue(); + assertThat((Boolean) new Json().toType("false", Boolean.class)).isFalse(); } @Test public void canReadANumber() { - assertEquals(Long.valueOf(42), new Json().toType("42", Number.class)); - assertEquals(Integer.valueOf(42), new Json().toType("42", Integer.class)); - assertEquals(Double.valueOf(42), new Json().toType("42", Double.class)); + assertThat((Number) new Json().toType("42", Number.class)).isEqualTo(Long.valueOf(42)); + assertThat((Integer) new Json().toType("42", Integer.class)).isEqualTo(Integer.valueOf(42)); + assertThat((Double) new Json().toType("42", Double.class)).isEqualTo(Double.valueOf(42)); } @Test @@ -86,7 +84,7 @@ public void canRoundTripNumbers() { System.out.println("converted = " + converted); Object remade = json.toType(converted, MAP_TYPE); - assertEquals(original, remade); + assertThat(remade).isEqualTo(original); } @Test @@ -95,11 +93,11 @@ public void roundTripAFirefoxOptions() { "moz:firefoxOptions", ImmutableMap.of( "prefs", ImmutableMap.of("foo.bar", 1))); String json = new Json().toJson(caps); - assertFalse(json, json.contains("1.0")); + assertThat(json).doesNotContain("1.0"); try (JsonInput input = new Json().newInput(new StringReader(json))) { json = new Json().toJson(input.read(Json.MAP_TYPE)); - assertFalse(json, json.contains("1.0")); + assertThat(json).doesNotContain("1.0"); } } @@ -115,8 +113,8 @@ public void shouldCoerceAListOfCapabilitiesIntoSomethingMutable() { System.out.println("raw = " + raw); List seen = json.toType(raw, new TypeToken>(){}.getType()); - assertEquals(expected, seen); - assertTrue(seen.get(0) instanceof MutableCapabilities); + assertThat(seen).isEqualTo(expected); + assertThat(seen.get(0)).isInstanceOf(MutableCapabilities.class); } @Test @@ -127,7 +125,7 @@ public void shouldUseBeanSettersToPopulateFields() { String raw = json.toJson(map); BeanWithSetter seen = json.toType(raw, BeanWithSetter.class); - assertEquals("fishy", seen.theName); + assertThat(seen.theName).isEqualTo("fishy"); } public static class BeanWithSetter { @@ -146,14 +144,14 @@ public void shouldAllowUserToPopulateFieldsDirectly() { String raw = json.toJson(map); BeanWithSetter seen = json.toType(raw, BeanWithSetter.class, PropertySetting.BY_FIELD); - assertEquals("fishy", seen.theName); + assertThat(seen.theName).isEqualTo("fishy"); } @Test public void testCanConstructASimpleString() { String text = new Json().toType("\"cheese\"", String.class); - assertThat(text, is("cheese")); + assertThat(text).isEqualTo("cheese"); } @SuppressWarnings("unchecked") @@ -164,9 +162,10 @@ public void testCanPopulateAMap() { toConvert.addProperty("foodstuff", "cheese"); Map map = new Json().toType(toConvert.toString(), Map.class); - assertThat(map.size(), is(2)); - assertThat(map, hasEntry("cheese", "brie")); - assertThat(map, hasEntry("foodstuff", "cheese")); + assertThat(map) + .hasSize(2) + .containsEntry("cheese", "brie") + .containsEntry("foodstuff", "cheese"); } @Test @@ -175,9 +174,9 @@ public void testCanPopulateAMapThatContainsNull() { toConvert.add("foo", JsonNull.INSTANCE); Map converted = new Json().toType(toConvert.toString(), Map.class); - assertEquals(1, converted.size()); - assertTrue(converted.containsKey("foo")); - assertNull(converted.get("foo")); + assertThat(converted.size()).isEqualTo(1); + assertThat(converted.containsKey("foo")).isTrue(); + assertThat(converted.get("foo")).isNull(); } @Test @@ -186,7 +185,7 @@ public void testCanPopulateASimpleBean() { toConvert.addProperty("value", "time"); SimpleBean bean = new Json().toType(toConvert.toString(), SimpleBean.class); - assertThat(bean.getValue(), is("time")); + assertThat(bean.getValue()).isEqualTo("time"); } @Test @@ -197,7 +196,7 @@ public void testWillSilentlyDiscardUnusedFieldsWhenPopulatingABean() { SimpleBean bean = new Json().toType(toConvert.toString(), SimpleBean.class); - assertThat(bean.getValue(), is("time")); + assertThat(bean.getValue()).isEqualTo("time"); } @Test @@ -207,7 +206,7 @@ public void testShouldSetPrimitiveValuesToo() { Map map = new Json().toType(toConvert.toString(), Map.class); - assertEquals(3L, map.get("magicNumber")); + assertThat(map.get("magicNumber")).isEqualTo(3L); } @Test @@ -220,8 +219,8 @@ public void testShouldPopulateFieldsOnNestedBeans() { ContainingBean bean = new Json().toType(toConvert.toString(), ContainingBean.class); - assertThat(bean.getName(), is("frank")); - assertThat(bean.getBean().getValue(), is("lots")); + assertThat(bean.getName()).isEqualTo("frank"); + assertThat(bean.getBean().getValue()).isEqualTo("lots"); } @Test @@ -233,7 +232,7 @@ public void testShouldProperlyFillInACapabilitiesObject() { Capabilities readCapabilities = new Json().toType(text, DesiredCapabilities.class); - assertEquals(capabilities, readCapabilities); + assertThat(readCapabilities).isEqualTo(capabilities); } @Test @@ -242,8 +241,8 @@ public void testShouldUseAMapToRepresentComplexObjects() { toModel.addProperty("thing", "hairy"); toModel.addProperty("hairy", "true"); - Map modelled = (Map) new Json().toType(toModel.toString(), Object.class); - assertEquals(2, modelled.size()); + Map modelled = new Json().toType(toModel.toString(), Object.class); + assertThat(modelled).hasSize(2); } @Test @@ -252,31 +251,23 @@ public void testShouldConvertAResponseWithAnElementInIt() { "{\"value\":{\"value\":\"\",\"text\":\"\",\"selected\":false,\"enabled\":true,\"id\":\"three\"},\"context\":\"con\",\"sessionId\":\"sess\"}"; Response converted = new Json().toType(json, Response.class); - Map value = (Map) converted.getValue(); - assertEquals("three", value.get("id")); + Map value = (Map) converted.getValue(); + assertThat(value).containsEntry("id", "three"); } @Test public void testShouldBeAbleToCopeWithStringsThatLookLikeBooleans() { - String json = - "{\"value\":\"false\",\"context\":\"foo\",\"sessionId\":\"1210083863107\"}"; - - try { - new Json().toType(json, Response.class); - } catch (Exception e) { - e.printStackTrace(); - fail("This should have worked"); - } + String json = "{\"value\":\"false\",\"context\":\"foo\",\"sessionId\":\"1210083863107\"}"; + new Json().toType(json, Response.class); } @Test public void testShouldBeAbleToSetAnObjectToABoolean() { - String json = - "{\"value\":true,\"context\":\"foo\",\"sessionId\":\"1210084658750\"}"; + String json = "{\"value\":true,\"context\":\"foo\",\"sessionId\":\"1210084658750\"}"; Response response = new Json().toType(json, Response.class); - assertThat(response.getValue(), is(true)); + assertThat(response.getValue()).isEqualTo(true); } @Test @@ -291,9 +282,9 @@ public void testCanHandleValueBeingAnArray() { String json = new Json().toJson(response); Response converted = new Json().toType(json, Response.class); - assertEquals("bar", response.getSessionId()); - assertEquals(2, ((List) converted.getValue()).size()); - assertEquals(1512, response.getStatus().intValue()); + assertThat(response.getSessionId()).isEqualTo("bar"); + assertThat(((List) converted.getValue())).hasSize(2); + assertThat(response.getStatus().intValue()).isEqualTo(1512); } @Test @@ -305,22 +296,17 @@ public void testShouldConvertObjectsInArraysToMaps() { List list = new Json().toType(rawJson, List.class); Object first = list.get(0); - assertTrue(first instanceof Map); - - Map map = (Map) first; - assertMapEntry(map, "name", "foo"); - assertMapEntry(map, "value", "bar"); - assertMapEntry(map, "domain", "localhost"); - assertMapEntry(map, "path", "/rooted"); - assertMapEntry(map, "secure", true); - assertMapEntry(map, "httpOnly", true); - assertMapEntry(map, "expiry", TimeUnit.MILLISECONDS.toSeconds(date.getTime())); - } + assertThat(first instanceof Map).isTrue(); - private void assertMapEntry(Map map, String key, Object expected) { - assertTrue("Missing key: " + key, map.containsKey(key)); - assertEquals("Wrong value for key: " + key + ": " + map.get(key).getClass().getName(), - expected, map.get(key)); + Map map = (Map) first; + assertThat(map) + .containsEntry("name", "foo") + .containsEntry("value", "bar") + .containsEntry("domain", "localhost") + .containsEntry("path", "/rooted") + .containsEntry("secure", true) + .containsEntry("httpOnly", true) + .containsEntry("expiry", TimeUnit.MILLISECONDS.toSeconds(date.getTime())); } @Test @@ -331,7 +317,7 @@ public void testShouldConvertAnArrayBackIntoAnArray() { Map reconstructed = new Json().toType(converted, Map.class); List trace = (List) reconstructed.get("stackTrace"); - assertTrue(trace.get(0) instanceof Map); + assertThat(trace.get(0)).isInstanceOf(Map.class); } @Test @@ -339,7 +325,7 @@ public void testShouldBeAbleToReconsituteASessionId() { String json = new Json().toJson(new SessionId("id")); SessionId sessionId = new Json().toType(json, SessionId.class); - assertEquals("id", sessionId.toString()); + assertThat(sessionId.toString()).isEqualTo("id"); } @Test @@ -352,11 +338,11 @@ public void testShouldBeAbleToConvertACommand() { String raw = new Json().toJson(original); Command converted = new Json().toType(raw, Command.class); - assertEquals(sessionId.toString(), converted.getSessionId().toString()); - assertEquals(original.getName(), converted.getName()); + assertThat(converted.getSessionId().toString()).isEqualTo(sessionId.toString()); + assertThat(converted.getName()).isEqualTo(original.getName()); - assertEquals(1, converted.getParameters().keySet().size()); - assertEquals("cheese", converted.getParameters().get("food")); + assertThat(converted.getParameters().keySet()).hasSize(1); + assertThat(converted.getParameters().get("food")).isEqualTo("cheese"); } @Test @@ -366,7 +352,7 @@ public void testShouldConvertCapabilitiesToAMapAndIncludeCustomValues() { String raw = new Json().toJson(caps); Capabilities converted = new Json().toType(raw, Capabilities.class); - assertEquals("fishy", converted.getCapability("furrfu")); + assertThat(converted.getCapability("furrfu")).isEqualTo("fishy"); } @Test @@ -384,11 +370,11 @@ public void testShouldParseCapabilitiesWithLoggingPreferences() { LoggingPreferences lp = (LoggingPreferences) converted.getCapability(CapabilityType.LOGGING_PREFS); - assertNotNull(lp); - assertEquals(Level.WARNING, lp.getLevel(LogType.BROWSER)); - assertEquals(Level.FINE, lp.getLevel(LogType.CLIENT)); - assertEquals(Level.ALL, lp.getLevel(LogType.DRIVER)); - assertEquals(Level.OFF, lp.getLevel(LogType.SERVER)); + assertThat(lp).isNotNull(); + assertThat(lp.getLevel(BROWSER)).isEqualTo(WARNING); + assertThat(lp.getLevel(CLIENT)).isEqualTo(FINE); + assertThat(lp.getLevel(DRIVER)).isEqualTo(ALL); + assertThat(lp.getLevel(SERVER)).isEqualTo(OFF); } @Test @@ -403,12 +389,12 @@ public void testShouldNotParseQuotedJsonObjectsAsActualJsonObjects() { String jsonStr = outer.toString(); Object convertedOuter = new Json().toType(jsonStr, Map.class); - assertThat(convertedOuter, instanceOf(Map.class)); + assertThat(convertedOuter).isInstanceOf(Map.class); Object convertedInner = ((Map) convertedOuter).get("inner"); - assertNotNull(convertedInner); - assertThat(convertedInner, instanceOf(String.class)); - assertThat(convertedInner.toString(), equalTo(inner.toString())); + assertThat(convertedInner).isNotNull(); + assertThat(convertedInner).isInstanceOf(String.class); + assertThat(convertedInner.toString()).isEqualTo(inner.toString()); } @Test @@ -425,13 +411,13 @@ public void shouldBeAbleToConvertASelenium3CommandToASelenium2Command() { Command converted = new Json().toType(stringified, Command.class); - assertEquals(expectedId, converted.getSessionId()); + assertThat(converted.getSessionId()).isEqualTo(expectedId); } @Test public void testShouldCallFromJsonMethodIfPresent() { JsonAware res = new Json().toType("\"converted\"", JsonAware.class); - assertEquals("\"converted\"", res.convertedValue); + assertThat(res.convertedValue).isEqualTo("\"converted\""); } // Test for issue 8187 @@ -443,9 +429,9 @@ public void testDecodingResponseWithNumbersInValueObject() { @SuppressWarnings("unchecked") Map value = (Map) response.getValue(); - assertEquals(96, value.get("width").intValue()); - assertEquals(46, value.get("height").intValue()); - assertEquals(46.19140625, value.get("height").doubleValue(), 0.00001); + assertThat(value.get("width").intValue()).isEqualTo(96); + assertThat(value.get("height").intValue()).isEqualTo(46); + assertThat(value.get("height").doubleValue()).isCloseTo(46.19140625, byLessThan(0.00001)); } @Test @@ -454,10 +440,10 @@ public void testShouldRecognizeNumericStatus() { "{\"status\":0,\"value\":\"cheese\"}", Response.class); - assertEquals(0, response.getStatus().intValue()); - assertEquals(new ErrorCodes().toState(0), response.getState()); + assertThat(response.getStatus().intValue()).isEqualTo(0); + assertThat(response.getState()).isEqualTo(new ErrorCodes().toState(0)); String value = (String) response.getValue(); - assertEquals("cheese", value); + assertThat(value).isEqualTo("cheese"); } @Test @@ -466,10 +452,10 @@ public void testShouldRecognizeStringStatus() { "{\"status\":\"success\",\"value\":\"cheese\"}", Response.class); - assertEquals(0, response.getStatus().intValue()); - assertEquals(new ErrorCodes().toState(0), response.getState()); + assertThat(response.getStatus().intValue()).isEqualTo(0); + assertThat(response.getState()).isEqualTo(new ErrorCodes().toState(0)); String value = (String) response.getValue(); - assertEquals("cheese", value); + assertThat(value).isEqualTo("cheese"); } @Test @@ -477,8 +463,8 @@ public void testShouldConvertInvalidSelectorError() { Response response = new Json().toType( "{\"state\":\"invalid selector\",\"message\":\"invalid xpath selector\"}", Response.class); - assertEquals(32, response.getStatus().intValue()); - assertEquals(new ErrorCodes().toState(32), response.getState()); + assertThat(response.getStatus().intValue()).isEqualTo(32); + assertThat(response.getState()).isEqualTo(new ErrorCodes().toState(32)); } @Test @@ -487,22 +473,22 @@ public void testShouldRecognizeStringState() { .toType( "{\"state\":\"success\",\"value\":\"cheese\"}", Response.class); - assertEquals("success", response.getState()); - assertEquals(0, response.getStatus().intValue()); + assertThat(response.getState()).isEqualTo("success"); + assertThat(response.getStatus().intValue()).isEqualTo(0); String value = (String) response.getValue(); - assertEquals("cheese", value); + assertThat(value).isEqualTo("cheese"); } @Test public void testNoStatusShouldBeNullInResponseObject() { Response response = new Json().toType("{\"value\":\"cheese\"}", Response.class); - assertNull(response.getStatus()); + assertThat(response.getStatus()).isNull(); } @Test public void canConvertAnEnumWithALowerCaseValue() { Proxy.ProxyType type = new Json().toType("\"pac\"", Proxy.ProxyType.class); - assertEquals(Proxy.ProxyType.PAC, type); + assertThat(type).isEqualTo(PAC); } @Test @@ -518,9 +504,9 @@ public void canCoerceSimpleValuesToStrings() { raw, new TypeToken>(){}.getType()); - assertEquals("true", roundTripped.get("boolean")); - assertEquals("42", roundTripped.get("integer")); - assertEquals("3.14", roundTripped.get("float")); + assertThat(roundTripped.get("boolean")).isEqualTo("true"); + assertThat(roundTripped.get("integer")).isEqualTo("42"); + assertThat(roundTripped.get("float")).isEqualTo("3.14"); } public static class SimpleBean { diff --git a/java/client/test/org/openqa/selenium/logging/AvailableLogsTest.java b/java/client/test/org/openqa/selenium/logging/AvailableLogsTest.java index 4fed8604fff94..6658ac8269284 100644 --- a/java/client/test/org/openqa/selenium/logging/AvailableLogsTest.java +++ b/java/client/test/org/openqa/selenium/logging/AvailableLogsTest.java @@ -17,8 +17,7 @@ package org.openqa.selenium.logging; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assume.assumeFalse; import static org.junit.Assume.assumeTrue; import static org.openqa.selenium.remote.CapabilityType.ENABLE_PROFILING_CAPABILITY; @@ -59,8 +58,8 @@ public void quitDriver() { public void browserLogShouldBeEnabledByDefault() { assumeFalse(isOldChromedriver(driver)); Set logTypes = driver.manage().logs().getAvailableLogTypes(); - assertTrue("Browser logs should be enabled by default", - logTypes.contains(LogType.BROWSER)); + assertThat(logTypes.contains(LogType.BROWSER)) + .describedAs("Browser logs should be enabled by default").isTrue(); } @Test @@ -69,8 +68,8 @@ public void clientLogShouldBeEnabledByDefault() { // Do one action to have *something* in the client logs. driver.get(pages.formPage); Set logTypes = driver.manage().logs().getAvailableLogTypes(); - assertTrue("Client logs should be enabled by default", - logTypes.contains(LogType.CLIENT)); + assertThat(logTypes.contains(LogType.CLIENT)) + .describedAs("Client logs should be enabled by default").isTrue(); boolean foundExecutingStatement = false; boolean foundExecutedStatement = false; for (LogEntry logEntry : driver.manage().logs().get(LogType.CLIENT)) { @@ -78,24 +77,24 @@ public void clientLogShouldBeEnabledByDefault() { foundExecutedStatement |= logEntry.toString().contains("Executed: "); } - assertTrue(foundExecutingStatement); - assertTrue(foundExecutedStatement); + assertThat(foundExecutingStatement).isTrue(); + assertThat(foundExecutedStatement).isTrue(); } @Test public void driverLogShouldBeEnabledByDefault() { assumeFalse(isOldChromedriver(driver)); Set logTypes = driver.manage().logs().getAvailableLogTypes(); - assertTrue("Remote driver logs should be enabled by default", - logTypes.contains(LogType.DRIVER)); + assertThat(logTypes.contains(LogType.DRIVER)) + .describedAs("Remote driver logs should be enabled by default").isTrue(); } @Test public void profilerLogShouldBeDisabledByDefault() { assumeFalse(isOldChromedriver(driver)); Set logTypes = driver.manage().logs().getAvailableLogTypes(); - assertFalse("Profiler logs should not be enabled by default", - logTypes.contains(LogType.PROFILER)); + assertThat(logTypes.contains(LogType.PROFILER)) + .describedAs("Profiler logs should not be enabled by default").isFalse(); } @Test @@ -105,7 +104,8 @@ public void shouldBeAbleToEnableProfilerLog() { Capabilities caps = new ImmutableCapabilities(ENABLE_PROFILING_CAPABILITY, true); localDriver = new WebDriverBuilder().get(caps); Set logTypes = localDriver.manage().logs().getAvailableLogTypes(); - assertTrue("Profiler log should be enabled", logTypes.contains(LogType.PROFILER)); + assertThat(logTypes.contains(LogType.PROFILER)) + .describedAs("Profiler log should be enabled").isTrue(); } @Test @@ -113,8 +113,8 @@ public void serverLogShouldBeEnabledByDefaultOnRemote() { assumeTrue(Boolean.getBoolean("selenium.browser.remote")); Set logTypes = driver.manage().logs().getAvailableLogTypes(); - assertTrue("Server logs should be enabled by default", - logTypes.contains(LogType.SERVER)); + assertThat(logTypes.contains(LogType.SERVER)) + .describedAs("Server logs should be enabled by default").isTrue(); } } diff --git a/java/client/test/org/openqa/selenium/logging/GetLogsTest.java b/java/client/test/org/openqa/selenium/logging/GetLogsTest.java index 14b4bc05c3b75..f3ae85d52c4c6 100644 --- a/java/client/test/org/openqa/selenium/logging/GetLogsTest.java +++ b/java/client/test/org/openqa/selenium/logging/GetLogsTest.java @@ -17,8 +17,7 @@ package org.openqa.selenium.logging; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assume.assumeFalse; import static org.junit.Assume.assumeTrue; import static org.openqa.selenium.testing.Driver.HTMLUNIT; @@ -68,9 +67,9 @@ public void logBufferShouldBeResetAfterEachGetLogCall() { LogEntries firstEntries = driver.manage().logs().get(logType); assumeTrue(firstEntries.getAll().size() > 0); LogEntries secondEntries = driver.manage().logs().get(logType); - assertFalse(String.format("There should be no overlapping log entries in " + - "consecutive get log calls for %s logs", logType), - LogEntriesChecks.hasOverlappingLogEntries(firstEntries, secondEntries)); + assertThat(hasOverlappingLogEntries(firstEntries, secondEntries)) + .describedAs("There should be no overlapping log entries in consecutive get log calls for %s logs", logType) + .isFalse(); } } @@ -86,15 +85,34 @@ public void differentLogsShouldNotContainTheSameLogEntries() { for (String firstLogType : logTypeToEntriesMap.keySet()) { for (String secondLogType : logTypeToEntriesMap.keySet()) { if (!firstLogType.equals(secondLogType)) { - assertFalse(String.format("Two different log types (%s, %s) should not " + - "contain the same log entries", firstLogType, secondLogType), - LogEntriesChecks.hasOverlappingLogEntries(logTypeToEntriesMap.get(firstLogType), - logTypeToEntriesMap.get(secondLogType))); + assertThat(hasOverlappingLogEntries(logTypeToEntriesMap.get(firstLogType), logTypeToEntriesMap.get(secondLogType))) + .describedAs("Two different log types (%s, %s) should not contain the same log entries", firstLogType, secondLogType) + .isFalse(); } } } } + /** + * Checks if there are overlapping entries in the given logs. + * + * @param firstLog The first log. + * @param secondLog The second log. + * @return true if an overlapping entry is discovered, otherwise false. + */ + private static boolean hasOverlappingLogEntries(LogEntries firstLog, LogEntries secondLog) { + for (LogEntry firstEntry : firstLog) { + for (LogEntry secondEntry : secondLog) { + if (firstEntry.getLevel().getName().equals(secondEntry.getLevel().getName()) && + firstEntry.getMessage().equals(secondEntry.getMessage()) && + firstEntry.getTimestamp() == secondEntry.getTimestamp()) { + return true; + } + } + } + return false; + } + @Test @NeedsLocalEnvironment public void turningOffLogShouldMeanNoLogMessages() { @@ -103,9 +121,9 @@ public void turningOffLogShouldMeanNoLogMessages() { for (String logType : logTypes) { createWebDriverWithLogging(logType, Level.OFF); LogEntries entries = localDriver.manage().logs().get(logType); - assertEquals(String.format("There should be no log entries for " + - "log type %s when logging is turned off.", logType), - 0, entries.getAll().size()); + assertThat(entries.getAll()) + .describedAs("There should be no log entries for log type %s when logging is turned off.", logType) + .hasSize(0); quitDriver(); } } diff --git a/java/client/test/org/openqa/selenium/logging/LogEntriesChecks.java b/java/client/test/org/openqa/selenium/logging/LogEntriesChecks.java deleted file mode 100644 index e0e5f34cbdae7..0000000000000 --- a/java/client/test/org/openqa/selenium/logging/LogEntriesChecks.java +++ /dev/null @@ -1,41 +0,0 @@ -// Licensed to the Software Freedom Conservancy (SFC) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The SFC licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package org.openqa.selenium.logging; - -public class LogEntriesChecks { - - /** - * Checks if there are overlapping entries in the given logs. - * - * @param firstLog The first log. - * @param secondLog The second log. - * @return true if an overlapping entry is discovered, otherwise false. - */ - public static boolean hasOverlappingLogEntries(LogEntries firstLog, LogEntries secondLog) { - for (LogEntry firstEntry : firstLog) { - for (LogEntry secondEntry : secondLog) { - if (firstEntry.getLevel().getName().equals(secondEntry.getLevel().getName()) && - firstEntry.getMessage().equals(secondEntry.getMessage()) && - firstEntry.getTimestamp() == secondEntry.getTimestamp()) { - return true; - } - } - } - return false; - } -} diff --git a/java/client/test/org/openqa/selenium/logging/LoggingTest.java b/java/client/test/org/openqa/selenium/logging/LoggingTest.java index 54557f228a7b3..8d2e7d7c2e5fa 100644 --- a/java/client/test/org/openqa/selenium/logging/LoggingTest.java +++ b/java/client/test/org/openqa/selenium/logging/LoggingTest.java @@ -17,38 +17,41 @@ package org.openqa.selenium.logging; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; +import static java.util.logging.Level.ALL; +import static java.util.logging.Level.FINE; +import static java.util.logging.Level.INFO; +import static java.util.logging.Level.OFF; +import static java.util.logging.Level.SEVERE; +import static java.util.logging.Level.WARNING; +import static org.assertj.core.api.Assertions.assertThat; +import static org.openqa.selenium.logging.LogLevelMapping.toLevel; import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; import java.util.logging.Level; -@RunWith(JUnit4.class) public class LoggingTest { @Test public void testLogLevelConversions() { - assertEquals(Level.ALL, LogLevelMapping.toLevel("ALL")); - assertEquals(Level.FINE, LogLevelMapping.toLevel("DEBUG")); - assertEquals(Level.INFO, LogLevelMapping.toLevel("INFO")); - assertEquals(Level.WARNING, LogLevelMapping.toLevel("WARNING")); - assertEquals(Level.SEVERE, LogLevelMapping.toLevel("SEVERE")); - assertEquals(Level.OFF, LogLevelMapping.toLevel("OFF")); + assertThat(toLevel("ALL")).isEqualTo(ALL); + assertThat(toLevel("DEBUG")).isEqualTo(FINE); + assertThat(toLevel("INFO")).isEqualTo(INFO); + assertThat(toLevel("WARNING")).isEqualTo(WARNING); + assertThat(toLevel("SEVERE")).isEqualTo(SEVERE); + assertThat(toLevel("OFF")).isEqualTo(OFF); } @Test public void canCompareLoggingPreferences() { LoggingPreferences prefs1 = new LoggingPreferences(); LoggingPreferences prefs2 = new LoggingPreferences(); - assertEquals(prefs1, prefs2); + assertThat(prefs2).isEqualTo(prefs1); prefs1.enable(LogType.BROWSER, Level.ALL); - assertNotEquals(prefs1, prefs2); + assertThat(prefs1).isNotEqualTo(prefs2); prefs2.enable(LogType.BROWSER, Level.ALL); - assertEquals(prefs1, prefs2); + assertThat(prefs2).isEqualTo(prefs1); } } diff --git a/java/client/test/org/openqa/selenium/logging/PerformanceLogTypeTest.java b/java/client/test/org/openqa/selenium/logging/PerformanceLogTypeTest.java index 6a7772fab86c7..9d1dca0e4f5de 100644 --- a/java/client/test/org/openqa/selenium/logging/PerformanceLogTypeTest.java +++ b/java/client/test/org/openqa/selenium/logging/PerformanceLogTypeTest.java @@ -17,9 +17,7 @@ package org.openqa.selenium.logging; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assume.assumeFalse; import static org.junit.Assume.assumeTrue; import static org.openqa.selenium.testing.Driver.HTMLUNIT; @@ -29,8 +27,6 @@ import static org.openqa.selenium.testing.TestUtilities.isChrome; import static org.openqa.selenium.testing.TestUtilities.isOldChromedriver; -import com.google.common.collect.Iterables; - import org.junit.After; import org.junit.Test; import org.openqa.selenium.Capabilities; @@ -64,8 +60,8 @@ public void quitDriver() { public void performanceLogShouldBeDisabledByDefault() { assumeFalse(isOldChromedriver(driver)); Set logTypes = driver.manage().logs().getAvailableLogTypes(); - assertFalse("Performance log should not be enabled by default", - logTypes.contains(LogType.PERFORMANCE)); + assertThat(logTypes.contains(LogType.PERFORMANCE)) + .describedAs("Performance log should not be enabled by default").isFalse(); } void createLocalDriverWithPerformanceLogType() { @@ -80,7 +76,8 @@ public void shouldBeAbleToEnablePerformanceLog() { assumeTrue(isChrome(driver) && !isOldChromedriver(driver)); // Only in the new chromedriver. createLocalDriverWithPerformanceLogType(); Set logTypes = localDriver.manage().logs().getAvailableLogTypes(); - assertTrue("Profiler log should be enabled", logTypes.contains(LogType.PERFORMANCE)); + assertThat(logTypes.contains(LogType.PERFORMANCE)) + .describedAs("Profiler log should be enabled").isTrue(); } @Test @@ -89,6 +86,6 @@ public void pageLoadShouldProducePerformanceLogEntries() { createLocalDriverWithPerformanceLogType(); localDriver.get(pages.simpleTestPage); LogEntries entries = localDriver.manage().logs().get(LogType.PERFORMANCE); - assertNotEquals(0, Iterables.size(entries)); + assertThat(entries).isNotEmpty(); } } diff --git a/java/client/test/org/openqa/selenium/logging/PerformanceLoggingMockTest.java b/java/client/test/org/openqa/selenium/logging/PerformanceLoggingMockTest.java index 6755d486bff3e..318b1028b3272 100644 --- a/java/client/test/org/openqa/selenium/logging/PerformanceLoggingMockTest.java +++ b/java/client/test/org/openqa/selenium/logging/PerformanceLoggingMockTest.java @@ -17,7 +17,7 @@ package org.openqa.selenium.logging; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -26,8 +26,6 @@ import com.google.common.collect.ImmutableSet; import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; import org.openqa.selenium.remote.DriverCommand; import org.openqa.selenium.remote.ExecuteMethod; import org.openqa.selenium.remote.RemoteLogs; @@ -35,7 +33,6 @@ import java.util.List; import java.util.logging.Level; -@RunWith(JUnit4.class) public class PerformanceLoggingMockTest { @Test @@ -49,15 +46,15 @@ public void testMergesRemoteLogs() { "timestamp", 1L, "message", "second"))); - LocalLogs localLogs = LocalLogs.getStoringLoggerInstance(ImmutableSet.of(LogType.PROFILER)); + LocalLogs localLogs = LocalLogs.getStoringLoggerInstance(ImmutableSet.of(LogType.PROFILER)); RemoteLogs logs = new RemoteLogs(executeMethod, localLogs); localLogs.addEntry(LogType.PROFILER, new LogEntry(Level.INFO, 0, "first")); localLogs.addEntry(LogType.PROFILER, new LogEntry(Level.INFO, 2, "third")); List entries = logs.get(LogType.PROFILER).getAll(); - assertEquals(3, entries.size()); + assertThat(entries).hasSize(3); for (int i = 0; i < entries.size(); ++i) { - assertEquals(i, entries.get(i).getTimestamp()); + assertThat(entries.get(i).getTimestamp()).isEqualTo(i); } } } diff --git a/java/client/test/org/openqa/selenium/logging/PerformanceLoggingTest.java b/java/client/test/org/openqa/selenium/logging/PerformanceLoggingTest.java index 1671dee6e985e..a7b85b340a272 100644 --- a/java/client/test/org/openqa/selenium/logging/PerformanceLoggingTest.java +++ b/java/client/test/org/openqa/selenium/logging/PerformanceLoggingTest.java @@ -17,10 +17,7 @@ package org.openqa.selenium.logging; -import static org.hamcrest.Matchers.greaterThan; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.openqa.selenium.remote.CapabilityType.ENABLE_PROFILING_CAPABILITY; import static org.openqa.selenium.testing.Driver.CHROME; import static org.openqa.selenium.testing.Driver.HTMLUNIT; @@ -40,7 +37,6 @@ import org.openqa.selenium.testing.JUnit4TestBase; import org.openqa.selenium.testing.drivers.WebDriverBuilder; -import java.util.Arrays; import java.util.stream.Collectors; import java.util.stream.StreamSupport; @@ -63,8 +59,9 @@ public void quitDriver() { @Test public void testDisabledProfilingDoesNotLog() { driver.get(pages.simpleTestPage); - assertEquals("Profiler should not log when disabled", - getProfilerEntries(driver).getAll().size(), 0); + assertThat(getProfilerEntries(driver).getAll()) + .describedAs("Profiler should not log when disabled") + .hasSize(0); } @Test @@ -77,8 +74,7 @@ public void testLogsSingleHttpCommand() { "\"command\": \"newSession\",\"startorend\": \"end\"", "\"command\": \"getLog\",\"startorend\": \"start\"", "\"command\": \"getLog\",\"startorend\": \"end\""}; - assertTrue("Profiler entries should contain: " + Arrays.toString(expected), - containsExpectedEntries(entries, expected)); + assertThat(containsExpectedEntries(entries, expected)).isTrue(); } /** @@ -108,8 +104,9 @@ public void testGetsYieldToPageLoadLogEntries() { startLoggingDriver(); loggingDriver.get(pages.formPage); loggingDriver.findElement(By.id("submitButton")).click(); - assertThat(getProfilerEntriesOfType(getProfilerEntries(loggingDriver), - EventType.YIELD_TO_PAGE_LOAD).size(), greaterThan(0)); + assertThat( + getProfilerEntriesOfType(getProfilerEntries(loggingDriver), EventType.YIELD_TO_PAGE_LOAD).size()) + .isGreaterThan(0); } private void startLoggingDriver() { diff --git a/java/client/test/org/openqa/selenium/mobile/NetworkConnectionTest.java b/java/client/test/org/openqa/selenium/mobile/NetworkConnectionTest.java index e3c32f9b7b0eb..8192f5e35de07 100644 --- a/java/client/test/org/openqa/selenium/mobile/NetworkConnectionTest.java +++ b/java/client/test/org/openqa/selenium/mobile/NetworkConnectionTest.java @@ -17,7 +17,8 @@ package org.openqa.selenium.mobile; -import org.junit.Assert; +import static org.assertj.core.api.Assertions.assertThat; + import org.junit.Assume; import org.junit.Before; import org.junit.Test; @@ -47,8 +48,9 @@ public void testToggleAirplaneMode() { networkConnectionDriver .setNetworkConnection(NetworkConnection.ConnectionType.AIRPLANE_MODE); } - Assert.assertEquals("airplane mode should have been toggled", !current.isAirplaneMode(), - modified.isAirplaneMode()); + assertThat(modified.isAirplaneMode()) + .describedAs("airplane mode should have been toggled") + .isNotEqualTo(current.isAirplaneMode()); } } diff --git a/java/client/test/org/openqa/selenium/net/LinuxEphemeralPortRangeDetectorTest.java b/java/client/test/org/openqa/selenium/net/LinuxEphemeralPortRangeDetectorTest.java index b78247a89068c..f29b2e7a69283 100644 --- a/java/client/test/org/openqa/selenium/net/LinuxEphemeralPortRangeDetectorTest.java +++ b/java/client/test/org/openqa/selenium/net/LinuxEphemeralPortRangeDetectorTest.java @@ -17,20 +17,16 @@ package org.openqa.selenium.net; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.openqa.selenium.Platform.LINUX; import org.junit.Assume; import org.junit.BeforeClass; import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; import org.openqa.selenium.Platform; import java.io.StringReader; -@RunWith(JUnit4.class) public class LinuxEphemeralPortRangeDetectorTest { @BeforeClass @@ -43,14 +39,14 @@ public void decodeEphemeralPorts() { String range ="1234 65533"; EphemeralPortRangeDetector ephemeralEphemeralPortDetector = new LinuxEphemeralPortRangeDetector(new StringReader(range)); - assertEquals( 1234, ephemeralEphemeralPortDetector.getLowestEphemeralPort()); - assertEquals( 65533, ephemeralEphemeralPortDetector.getHighestEphemeralPort()); + assertThat(ephemeralEphemeralPortDetector.getLowestEphemeralPort()).isEqualTo(1234); + assertThat(ephemeralEphemeralPortDetector.getHighestEphemeralPort()).isEqualTo(65533); } @Test public void currentValues() { LinuxEphemeralPortRangeDetector detector = LinuxEphemeralPortRangeDetector.getInstance(); - assertTrue( detector.getLowestEphemeralPort() > 1024); - assertTrue( detector.getHighestEphemeralPort() < 65536); + assertThat( detector.getLowestEphemeralPort()).isGreaterThan(1024); + assertThat( detector.getHighestEphemeralPort()).isLessThan(65536); } } diff --git a/java/client/test/org/openqa/selenium/net/NetworkUtilsTest.java b/java/client/test/org/openqa/selenium/net/NetworkUtilsTest.java index d845046550cc3..1295b4902819a 100644 --- a/java/client/test/org/openqa/selenium/net/NetworkUtilsTest.java +++ b/java/client/test/org/openqa/selenium/net/NetworkUtilsTest.java @@ -16,95 +16,82 @@ // under the License. package org.openqa.selenium.net; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; -@RunWith(JUnit4.class) public class NetworkUtilsTest { @Test public void testGetPrivateLocalAddress() { NetworkUtils networkUtils = new NetworkUtils(StubNetworkInterfaceProvider.getUbuntu1010SingleNICAndWlan()); - String s = networkUtils.obtainLoopbackIp4Address(); - assertEquals("127.0.0.3", s); - assertEquals("chunky.local", networkUtils.getNonLoopbackAddressOfThisMachine()); + assertThat(networkUtils.obtainLoopbackIp4Address()).isEqualTo("127.0.0.3"); + assertThat(networkUtils.getNonLoopbackAddressOfThisMachine()).isEqualTo("chunky.local"); } @Test public void testPrivateLocalAddress() { NetworkUtils networkUtils = new NetworkUtils(StubNetworkInterfaceProvider.getWindowsXpWithIp4Only()); - String s = networkUtils.obtainLoopbackIp4Address(); - assertEquals("localXhost", s); - assertEquals("myip4.mydomain.com", networkUtils.getNonLoopbackAddressOfThisMachine()); + assertThat(networkUtils.obtainLoopbackIp4Address()).isEqualTo("localXhost"); + assertThat(networkUtils.getNonLoopbackAddressOfThisMachine()).isEqualTo("myip4.mydomain.com"); } @Test public void testRHELBox() { NetworkUtils networkUtils = new NetworkUtils(StubNetworkInterfaceProvider.getRHEL5Box()); - String s = networkUtils.obtainLoopbackIp4Address(); - assertEquals("localhost.localdomain", s); - assertEquals("woz-woz23", networkUtils.getNonLoopbackAddressOfThisMachine()); + assertThat(networkUtils.obtainLoopbackIp4Address()).isEqualTo("localhost.localdomain"); + assertThat(networkUtils.getNonLoopbackAddressOfThisMachine()).isEqualTo("woz-woz23"); } @Test public void testSolarisBox() { NetworkUtils networkUtils = new NetworkUtils(StubNetworkInterfaceProvider.getSolarisBox()); - String s = networkUtils.obtainLoopbackIp4Address(); - assertEquals("localhost", s); - assertEquals("woz-woz01-adm", networkUtils.getNonLoopbackAddressOfThisMachine()); + assertThat(networkUtils.obtainLoopbackIp4Address()).isEqualTo("localhost"); + assertThat(networkUtils.getNonLoopbackAddressOfThisMachine()).isEqualTo("woz-woz01-adm"); } @Test public void testUbuntu9X() { NetworkUtils networkUtils = new NetworkUtils(StubNetworkInterfaceProvider.getUbuntu09XSingleNIC()); - String s = networkUtils.obtainLoopbackIp4Address(); - assertEquals("127.0.0.1", s); - assertEquals("157.120.171.97", networkUtils.getNonLoopbackAddressOfThisMachine()); + assertThat(networkUtils.obtainLoopbackIp4Address()).isEqualTo("127.0.0.1"); + assertThat(networkUtils.getNonLoopbackAddressOfThisMachine()).isEqualTo("157.120.171.97"); } @Test public void testOsXSnowLeopard() { NetworkUtils networkUtils = new NetworkUtils(StubNetworkInterfaceProvider.getOsXWiredAndWireless()); - String s = networkUtils.obtainLoopbackIp4Address(); - assertEquals("127.0.0.1", s); - assertEquals("192.168.4.1", networkUtils.getNonLoopbackAddressOfThisMachine()); + assertThat(networkUtils.obtainLoopbackIp4Address()).isEqualTo("127.0.0.1"); + assertThat(networkUtils.getNonLoopbackAddressOfThisMachine()).isEqualTo("192.168.4.1"); } @Test public void testFreeBsd() { NetworkUtils networkUtils = new NetworkUtils(StubNetworkInterfaceProvider.getFreeBsd()); - String s = networkUtils.obtainLoopbackIp4Address(); - assertEquals("localhost.apache.org", s); - assertEquals("192.168.0.4", networkUtils.getNonLoopbackAddressOfThisMachine()); + assertThat(networkUtils.obtainLoopbackIp4Address()).isEqualTo("localhost.apache.org"); + assertThat(networkUtils.getNonLoopbackAddressOfThisMachine()).isEqualTo("192.168.0.4"); } @Test public void testVistaBox() { NetworkUtils networkUtils = new NetworkUtils(StubNetworkInterfaceProvider.getVistaBox()); - String s = networkUtils.obtainLoopbackIp4Address(); - assertEquals("127.0.0.1", s); - assertEquals("woz134", networkUtils.getNonLoopbackAddressOfThisMachine()); + assertThat(networkUtils.obtainLoopbackIp4Address()).isEqualTo("127.0.0.1"); + assertThat(networkUtils.getNonLoopbackAddressOfThisMachine()).isEqualTo("woz134"); } @Test public void testWindows7Box() { NetworkUtils networkUtils = new NetworkUtils(StubNetworkInterfaceProvider.getWindows7Box()); - String s = networkUtils.obtainLoopbackIp4Address(); - assertEquals("127.0.0.1", s); - assertEquals("192.168.1.102", networkUtils.getNonLoopbackAddressOfThisMachine()); + assertThat(networkUtils.obtainLoopbackIp4Address()).isEqualTo("127.0.0.1"); + assertThat(networkUtils.getNonLoopbackAddressOfThisMachine()).isEqualTo("192.168.1.102"); } @Test public void testOpenSuseBoxIssue1181() { NetworkUtils networkUtils = new NetworkUtils(StubNetworkInterfaceProvider.getOpenSuseBoxFromIssue1181()); - String s = networkUtils.obtainLoopbackIp4Address(); - assertEquals("localhost.localdomain", s); + assertThat(networkUtils.obtainLoopbackIp4Address()).isEqualTo("localhost.localdomain"); } } diff --git a/java/client/test/org/openqa/selenium/net/UrlCheckerTest.java b/java/client/test/org/openqa/selenium/net/UrlCheckerTest.java index 491e65efd3c99..a21a8a72d6648 100644 --- a/java/client/test/org/openqa/selenium/net/UrlCheckerTest.java +++ b/java/client/test/org/openqa/selenium/net/UrlCheckerTest.java @@ -18,8 +18,7 @@ import static java.lang.System.currentTimeMillis; import static java.nio.charset.StandardCharsets.UTF_8; -import static org.hamcrest.Matchers.lessThan; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.openqa.selenium.remote.http.HttpMethod.GET; import org.junit.After; @@ -66,7 +65,7 @@ public void testWaitUntilAvailableIsTimely() throws Exception { long start = currentTimeMillis(); urlChecker.waitUntilAvailable(10, TimeUnit.SECONDS, url); long elapsed = currentTimeMillis() - start; - assertThat(elapsed, lessThan(UrlChecker.CONNECT_TIMEOUT_MS + 100L)); // threshold + assertThat(elapsed).isLessThan(UrlChecker.CONNECT_TIMEOUT_MS + 100L); // threshold } @Test @@ -84,7 +83,7 @@ public void testWaitUntilUnavailableIsTimely() throws Exception { long start = currentTimeMillis(); urlChecker.waitUntilUnavailable(10, TimeUnit.SECONDS, url); long elapsed = currentTimeMillis() - start; - assertThat(elapsed, lessThan(UrlChecker.CONNECT_TIMEOUT_MS + delay + 200L)); // threshold + assertThat(elapsed).isLessThan(UrlChecker.CONNECT_TIMEOUT_MS + delay + 200L); // threshold } @After diff --git a/java/client/test/org/openqa/selenium/opera/BUCK b/java/client/test/org/openqa/selenium/opera/BUCK index 317eab5092437..b7391e1b5af9e 100644 --- a/java/client/test/org/openqa/selenium/opera/BUCK +++ b/java/client/test/org/openqa/selenium/opera/BUCK @@ -19,6 +19,7 @@ java_library(name = 'tests', '//java/client/src/org/openqa/selenium/opera:opera', '//java/client/src/org/openqa/selenium/remote:remote', '//java/client/test/org/openqa/selenium/testing:test-base', + '//third_party/java/assertj:assertj', '//third_party/java/gson:gson', '//third_party/java/junit:junit', ], diff --git a/java/client/test/org/openqa/selenium/opera/OperaOptionsFunctionalTest.java b/java/client/test/org/openqa/selenium/opera/OperaOptionsFunctionalTest.java index 38b075d01d2f3..73b0eedbfdba4 100644 --- a/java/client/test/org/openqa/selenium/opera/OperaOptionsFunctionalTest.java +++ b/java/client/test/org/openqa/selenium/opera/OperaOptionsFunctionalTest.java @@ -17,8 +17,7 @@ package org.openqa.selenium.opera; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import org.junit.After; import org.junit.Test; @@ -47,7 +46,7 @@ public void canStartOperaWithCustomOptions() { driver.get(pages.clickJacker); Object userAgent = driver.executeScript("return window.navigator.userAgent"); - assertEquals("foo;bar", userAgent); + assertThat(userAgent).isEqualTo("foo;bar"); } @NeedsLocalEnvironment @@ -55,9 +54,8 @@ public void canStartOperaWithCustomOptions() { public void optionsStayEqualAfterSerialization() { OperaOptions options1 = new OperaOptions(); OperaOptions options2 = new OperaOptions(); - assertTrue("empty opera options should be equal", options1.equals(options2)); + assertThat(options1).isEqualTo(options2); options1.asMap(); - assertTrue("empty opera options after one is .toJson() should be equal", - options1.equals(options2)); + assertThat(options1).isEqualTo(options2); } } diff --git a/java/client/test/org/openqa/selenium/os/CommandLineTest.java b/java/client/test/org/openqa/selenium/os/CommandLineTest.java index 5d1250962d044..6d4d6a49990b7 100644 --- a/java/client/test/org/openqa/selenium/os/CommandLineTest.java +++ b/java/client/test/org/openqa/selenium/os/CommandLineTest.java @@ -17,20 +17,19 @@ package org.openqa.selenium.os; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; +import static java.lang.System.getenv; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.openqa.selenium.os.CommandLine.getLibraryPathPropertyName; import org.junit.Assume; import org.junit.Before; import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; import org.openqa.selenium.Platform; import java.util.HashMap; import java.util.Map; -@RunWith(JUnit4.class) public class CommandLineTest { private static String testExecutable; @@ -46,12 +45,9 @@ public void testSetEnvironmentVariableWithNullKeyThrows() { String key = null; String value = "Bar"; CommandLine commandLine = new CommandLine(testExecutable); - try { - commandLine.setEnvironmentVariable(key, value); - } catch (IllegalArgumentException iae) { - assertFalse(commandLine.getEnvironment() - .containsValue(value)); - } + assertThatExceptionOfType(IllegalArgumentException.class) + .isThrownBy(() -> commandLine.setEnvironmentVariable(key, value)); + assertThat(commandLine.getEnvironment()).doesNotContainValue(value); } @Test @@ -59,12 +55,9 @@ public void testSetEnvironmentVariableWithNullValueThrows() { String key = "Foo"; String value = null; CommandLine commandLine = new CommandLine(testExecutable); - try { - commandLine.setEnvironmentVariable(key, value); - } catch (IllegalArgumentException iae) { - assertFalse(commandLine.getEnvironment() - .containsKey(key)); - } + assertThatExceptionOfType(IllegalArgumentException.class) + .isThrownBy(() -> commandLine.setEnvironmentVariable(key, value)); + assertThat(commandLine.getEnvironment()).doesNotContainKey(key); } @Test @@ -73,8 +66,7 @@ public void testSetEnvironmentVariableWithNonNullValueSets() { String value = "Bar"; CommandLine commandLine = new CommandLine(testExecutable); commandLine.setEnvironmentVariable(key, value); - assertEquals(value, - commandLine.getEnvironment().get(key)); + assertThat(commandLine.getEnvironment()).containsEntry(key, value); } @Test @@ -83,12 +75,9 @@ public void testSetEnvironmentVariablesWithNullValueThrows() { input.put("key1", "value1"); input.put("key2", null); CommandLine commandLine = new CommandLine(testExecutable); - try { - commandLine.setEnvironmentVariables(input); - } catch (IllegalArgumentException iae) { - assertFalse(commandLine.getEnvironment() - .containsKey("key2")); - } + assertThatExceptionOfType(IllegalArgumentException.class) + .isThrownBy(() -> commandLine.setEnvironmentVariables(input)); + assertThat(commandLine.getEnvironment()).doesNotContainKey("key2"); } @Test @@ -98,35 +87,25 @@ public void testSetEnvironmentVariablesWithNonNullValueSetsAll() { input.put("key2", "value2"); CommandLine commandLine = new CommandLine(testExecutable); commandLine.setEnvironmentVariables(input); - assertEquals("value1", - commandLine.getEnvironment().get("key1")); - assertEquals("value2", - commandLine.getEnvironment().get("key2")); + assertThat(commandLine.getEnvironment()) + .containsEntry("key1", "value1") + .containsEntry("key2", "value2"); } @Test public void testSetDynamicLibraryPathWithNullValueIgnores() { String value = null; CommandLine commandLine = new CommandLine(testExecutable); - try { - commandLine.setDynamicLibraryPath(value); - } catch (IllegalArgumentException iae) { - assertFalse(commandLine.getEnvironment() - .containsKey(CommandLine.getLibraryPathPropertyName())); - } + commandLine.setDynamicLibraryPath(value); + assertThat(commandLine.getEnvironment()).doesNotContainKey(getLibraryPathPropertyName()); } @Test public void testSetDynamicLibraryPathWithNonNullValueSets() { String value = "Bar"; CommandLine commandLine = new CommandLine(testExecutable); - try { - commandLine.setDynamicLibraryPath(value); - } catch (IllegalArgumentException iae) { - assertEquals(value, - commandLine.getEnvironment() - .get(CommandLine.getLibraryPathPropertyName())); - } + commandLine.setDynamicLibraryPath(value); + assertThat(commandLine.getEnvironment().get(getLibraryPathPropertyName())).isEqualTo(value); } @Test @@ -141,7 +120,8 @@ public void canUpdateLibraryPath() { Assume.assumeTrue(Platform.getCurrent().is(Platform.WINDOWS)); CommandLine commandLine = new CommandLine(testExecutable); commandLine.updateDynamicLibraryPath("C:\\My\\Tools"); - assertEquals(String.format("%s;%s", System.getenv("PATH"), "C:\\My\\Tools"), - commandLine.getEnvironment().get(CommandLine.getLibraryPathPropertyName())); + assertThat(commandLine.getEnvironment()) + .containsEntry(getLibraryPathPropertyName(), + String.format("%s;%s", getenv("PATH"), "C:\\My\\Tools")); } } diff --git a/java/client/test/org/openqa/selenium/os/WindowsUtilsUnitTest.java b/java/client/test/org/openqa/selenium/os/WindowsUtilsUnitTest.java index 945201ee3a7d9..25498a7f07ba3 100644 --- a/java/client/test/org/openqa/selenium/os/WindowsUtilsUnitTest.java +++ b/java/client/test/org/openqa/selenium/os/WindowsUtilsUnitTest.java @@ -16,42 +16,24 @@ // under the License. package org.openqa.selenium.os; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; -import org.junit.Before; +import org.junit.Assume; import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; import java.util.Properties; -import java.util.regex.Matcher; -import java.util.regex.Pattern; -@RunWith(JUnit4.class) public class WindowsUtilsUnitTest { - private int majorVersion; - private int minorVersion; - private Pattern WIN_OS_VERSION = Pattern.compile("^(\\d)+\\.(\\d)+$"); + @Test + public void testLoadEnvironment() { + Assume.assumeTrue(WindowsUtils.thisIsWindows()); - @Before - public void setUp() { - if (!WindowsUtils.thisIsWindows()) return; String osVersion = System.getProperty("os.version"); - Matcher m = WIN_OS_VERSION.matcher(osVersion); - if (!m.find()) fail("osVersion doesn't look right: " + osVersion); - majorVersion = Integer.parseInt(m.group(1)); - minorVersion = Integer.parseInt(m.group(2)); - } + assertThat(osVersion.matches("^(\\d)+\\.(\\d)+$")); - @Test - public void testLoadEnvironment() { - if (!WindowsUtils.thisIsWindows()) return; Properties p = WindowsUtils.loadEnvironment(); - assertFalse("Environment appears to be empty!", p.isEmpty()); - assertNotNull("SystemRoot env var apparently not set on Windows!", - WindowsUtils.findSystemRoot()); + assertThat(p).isNotEmpty(); + assertThat(WindowsUtils.findSystemRoot()).isNotNull(); } } diff --git a/java/client/test/org/openqa/selenium/remote/AugmenterTest.java b/java/client/test/org/openqa/selenium/remote/AugmenterTest.java index e3b3b68bfaa51..58d7e7316e2e2 100644 --- a/java/client/test/org/openqa/selenium/remote/AugmenterTest.java +++ b/java/client/test/org/openqa/selenium/remote/AugmenterTest.java @@ -17,12 +17,8 @@ package org.openqa.selenium.remote; -import static org.hamcrest.Matchers.not; -import static org.hamcrest.Matchers.sameInstance; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotSame; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.mockito.Mockito.mock; import static org.openqa.selenium.remote.CapabilityType.SUPPORTS_JAVASCRIPT; import static org.openqa.selenium.remote.DriverCommand.FIND_ELEMENT; @@ -30,8 +26,6 @@ import com.google.common.collect.ImmutableMap; import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; import org.openqa.selenium.By; import org.openqa.selenium.Capabilities; import org.openqa.selenium.ImmutableCapabilities; @@ -42,7 +36,6 @@ import java.lang.reflect.Method; import java.util.HashMap; -@RunWith(JUnit4.class) public class AugmenterTest extends BaseAugmenterTest { @Override @@ -105,20 +98,15 @@ public InterfaceImplementation getImplementation(Object value) { augmenter.addDriverAugmentation(CapabilityType.SUPPORTS_JAVASCRIPT, augmentation); WebDriver returned = augmenter.augment(driver); - assertNotSame(driver, returned); - assertEquals("StubTitle", returned.getTitle()); + assertThat(returned).isNotSameAs(driver); + assertThat(returned.getTitle()).isEqualTo("StubTitle"); returned.quit(); // Should not fail because it's intercepted. // Verify original is unmodified. - boolean threw = false; - try { - driver.quit(); - } catch (AssertionError expected) { - assertTrue(expected.getMessage().startsWith("Unexpected method invocation")); - threw = true; - } - assertTrue("Did not throw", threw); + assertThatExceptionOfType(AssertionError.class) + .isThrownBy(driver::quit) + .withMessageStartingWith("Unexpected method invocation"); } @Test @@ -129,7 +117,7 @@ public void shouldNotAugmentRemoteWebDriverWithoutExtraCapabilities() { WebDriver augmentedDriver = getAugmenter().augment(driver); - assertThat(augmentedDriver, sameInstance(driver)); + assertThat(augmentedDriver).isSameAs(driver); } @Test @@ -140,7 +128,7 @@ public void shouldAugmentRemoteWebDriverWithExtraCapabilities() { WebDriver augmentedDriver = getAugmenter().augment(driver); - assertThat(augmentedDriver, not(sameInstance(driver))); + assertThat(augmentedDriver).isNotSameAs(driver); } public static class RemoteWebDriverSubclass extends RemoteWebDriver { @@ -157,6 +145,6 @@ public void shouldNotAugmentSubclassesOfRemoteWebDriver() { WebDriver augmentedDriver = getAugmenter().augment(driver); - assertThat(augmentedDriver, sameInstance(driver)); + assertThat(augmentedDriver).isSameAs(driver); } } diff --git a/java/client/test/org/openqa/selenium/remote/BUCK b/java/client/test/org/openqa/selenium/remote/BUCK index befb01abcd300..70d0db6341fca 100644 --- a/java/client/test/org/openqa/selenium/remote/BUCK +++ b/java/client/test/org/openqa/selenium/remote/BUCK @@ -15,7 +15,7 @@ java_test(name = 'common-tests', '//java/client/src/org/openqa/selenium/remote:remote', '//third_party/java/gson:gson', '//third_party/java/guava:guava', - '//third_party/java/hamcrest:hamcrest-library', + '//third_party/java/assertj:assertj', '//third_party/java/httpcomponents:httpclient', '//third_party/java/junit:junit', ]) @@ -56,7 +56,7 @@ java_test(name = 'client-tests', '//java/client/test/org/openqa/selenium/testing:test-base', '//third_party/java/gson:gson', '//third_party/java/guava:guava', - '//third_party/java/hamcrest:hamcrest-library', + '//third_party/java/assertj:assertj', '//third_party/java/jetty:jetty', '//third_party/java/junit:junit', '//third_party/java/mockito:mockito-core', diff --git a/java/client/test/org/openqa/selenium/remote/BaseAugmenterTest.java b/java/client/test/org/openqa/selenium/remote/BaseAugmenterTest.java index f2f67497021f4..eb333214bb43c 100644 --- a/java/client/test/org/openqa/selenium/remote/BaseAugmenterTest.java +++ b/java/client/test/org/openqa/selenium/remote/BaseAugmenterTest.java @@ -17,12 +17,7 @@ package org.openqa.selenium.remote; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotSame; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import com.google.common.collect.ImmutableMap; @@ -40,6 +35,7 @@ import org.openqa.selenium.WebElement; import java.util.ArrayList; +import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -52,7 +48,7 @@ public void shouldReturnANormalWebDriverUntouched() { WebDriver returned = getAugmenter().augment(driver); - assertSame(driver, returned); + assertThat(returned).isSameAs(driver); } @Test @@ -64,8 +60,8 @@ public void shouldAddInterfaceFromCapabilityIfNecessary() { augmenter.addDriverAugmentation("magic.numbers", new AddsMagicNumberHolder()); WebDriver returned = augmenter.augment(driver); - assertNotSame(driver, returned); - assertTrue(returned instanceof TakesScreenshot); + assertThat(returned).isNotSameAs(driver); + assertThat(returned).isInstanceOf(TakesScreenshot.class); } @Test @@ -77,8 +73,8 @@ public void shouldNotAddInterfaceWhenBooleanValueForItIsFalse() { augmenter.addDriverAugmentation("magic.numbers", new AddsMagicNumberHolder()); WebDriver returned = augmenter.augment(driver); - assertSame(driver, returned); - assertFalse(returned instanceof MagicNumberHolder); + assertThat(returned).isSameAs(driver); + assertThat(returned).isNotInstanceOf(MagicNumberHolder.class); } @Test @@ -100,7 +96,7 @@ public InterfaceImplementation getImplementation(Object value) { WebDriver returned = augmenter.augment(driver); String text = ((MyInterface) returned).getHelloWorld(); - assertEquals("Hello World", text); + assertThat(text).isEqualTo("Hello World"); } @Test @@ -114,7 +110,7 @@ public void shouldDelegateUnmatchedMethodCallsToDriverImplementation() { augmenter.addDriverAugmentation("magic.numbers", new AddsMagicNumberHolder()); WebDriver returned = augmenter.augment(driver); - assertEquals("Title", returned.getTitle()); + assertThat(returned.getTitle()).isEqualTo("Title"); } @Test(expected = NoSuchElementException.class) @@ -140,7 +136,7 @@ public void shouldLeaveAnUnAugmentableElementAlone() { WebElement returned = getAugmenter().augment(element); - assertSame(element, returned); + assertThat(returned).isSameAs(element); } @Test @@ -172,10 +168,9 @@ public Capabilities getCapabilities() { WebElement returned = augmenter.augment(element); - assertTrue(returned instanceof MyInterface); + assertThat(returned).isInstanceOf(MyInterface.class); - executor.expect(DriverCommand.CLICK_ELEMENT, ImmutableMap.of("id", "1234"), - null); + executor.expect(DriverCommand.CLICK_ELEMENT, ImmutableMap.of("id", "1234"), null); returned.click(); } @@ -185,17 +180,13 @@ public void shouldCopyFieldsFromTemplateInstanceIntoChildInstance() { driver.setMagicNumber(3); MagicNumberHolder holder = (MagicNumberHolder) getAugmenter().augment(driver); - assertEquals(3, holder.getMagicNumber()); + assertThat(holder.getMagicNumber()).isEqualTo(3); } @Test public void shouldNotChokeOnFinalFields() { WithFinals withFinals = new WithFinals(); - try { - getAugmenter().augment(withFinals); - } catch (Exception e) { - fail("This is not expected: " + e.getMessage()); - } + getAugmenter().augment(withFinals); } @@ -205,30 +196,30 @@ public void shouldBeAbleToAugmentMultipleTimes() { StubExecutor stubExecutor = new StubExecutor(caps); stubExecutor.expect(DriverCommand.GET_SCREEN_ORIENTATION, - ImmutableMap.of(), - ScreenOrientation.PORTRAIT.name()); + Collections.emptyMap(), + ScreenOrientation.PORTRAIT.name()); RemoteWebDriver driver = new RemoteWebDriver(stubExecutor, caps); BaseAugmenter augmenter = getAugmenter(); augmenter.addDriverAugmentation("canRotate", new AddRotatable()); WebDriver augmented = augmenter.augment(driver); - assertNotSame(augmented, driver); - assertTrue(augmented instanceof Rotatable); - assertFalse(augmented instanceof MagicNumberHolder); + assertThat(driver).isNotSameAs(augmented); + assertThat(augmented).isInstanceOf(Rotatable.class); + assertThat(augmented).isNotInstanceOf(MagicNumberHolder.class); augmenter = getAugmenter(); augmenter.addDriverAugmentation("magic.numbers", new AddsMagicNumberHolder()); WebDriver augmentedAgain = augmenter.augment(augmented); - assertNotSame(augmentedAgain, augmented); - assertTrue(augmentedAgain instanceof Rotatable); - assertTrue(augmentedAgain instanceof MagicNumberHolder); + assertThat(augmented).isNotSameAs(augmentedAgain); + assertThat(augmentedAgain).isInstanceOf(Rotatable.class); + assertThat(augmentedAgain).isInstanceOf(MagicNumberHolder.class); ((Rotatable) augmentedAgain).getOrientation(); // Should not throw. - assertSame(driver.getCapabilities(), - ((HasCapabilities) augmentedAgain).getCapabilities()); + assertThat(((HasCapabilities) augmentedAgain).getCapabilities()) + .isSameAs(driver.getCapabilities()); } protected static class StubExecutor implements CommandExecutor { @@ -255,8 +246,7 @@ public Response execute(Command command) { } } - fail("Unexpected method invocation: " + command); - return null; // never reached + throw new AssertionError("Unexpected method invocation: " + command); } public void expect(String commandName, Map args, Object returnValue) { diff --git a/java/client/test/org/openqa/selenium/remote/DesiredCapabilitiesTest.java b/java/client/test/org/openqa/selenium/remote/DesiredCapabilitiesTest.java index fbddcdcb334c6..4723f86eaf90b 100644 --- a/java/client/test/org/openqa/selenium/remote/DesiredCapabilitiesTest.java +++ b/java/client/test/org/openqa/selenium/remote/DesiredCapabilitiesTest.java @@ -17,25 +17,20 @@ package org.openqa.selenium.remote; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; + +import com.google.common.collect.ImmutableMap; import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; import org.openqa.selenium.Capabilities; import org.openqa.selenium.Platform; import org.openqa.selenium.WebDriver; import org.openqa.selenium.logging.LoggingPreferences; -import java.util.HashMap; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.logging.Level; -@RunWith(JUnit4.class) public class DesiredCapabilitiesTest { @Test @@ -46,7 +41,7 @@ public void testAddingTheSameCapabilityToAMapTwiceShouldResultInOneEntry() { capabilitiesToDriver.put(DesiredCapabilities.firefox(), WebDriver.class); capabilitiesToDriver.put(DesiredCapabilities.firefox(), WebDriver.class); - assertEquals(1, capabilitiesToDriver.size()); + assertThat(capabilitiesToDriver).hasSize(1); } @Test @@ -58,8 +53,8 @@ public void testAugmentingCapabilitiesReturnsNewCapabilities() { extraCapabilities.setCapability("Platform", "any"); origCapabilities.merge(extraCapabilities); - assertEquals("firefox", origCapabilities.getCapability("Browser")); - assertEquals("any", origCapabilities.getCapability("Platform")); + assertThat(origCapabilities.getCapability("Browser")).isEqualTo("firefox"); + assertThat(origCapabilities.getCapability("Platform")).isEqualTo("any"); } @Test @@ -67,7 +62,7 @@ public void testCopyConstructorWithNullArgument() { DesiredCapabilities origCapabilities = new DesiredCapabilities((Capabilities) null); origCapabilities.setCapability("Browser", "firefox"); - assertEquals("firefox", origCapabilities.getCapability("Browser")); + assertThat(origCapabilities.getCapability("Browser")).isEqualTo("firefox"); } @Test @@ -78,85 +73,75 @@ public void testCopyConstructorDoesNotAliasToArgument() { DesiredCapabilities newCapabilities = new DesiredCapabilities(origCapabilities); origCapabilities.setCapability("Browser", "ie"); - assertEquals("ie", origCapabilities.getCapability("Browser")); - assertEquals("firefox", newCapabilities.getCapability("Browser")); + assertThat(origCapabilities.getCapability("Browser")).isEqualTo("ie"); + assertThat(newCapabilities.getCapability("Browser")).isEqualTo("firefox"); } @Test public void testExtractDebugLogLevelFromCapabilityMap() { - Map capabilitiesMap = new HashMap() {{ - put(CapabilityType.LOGGING_PREFS, new HashMap() {{ - put("browser", "DEBUG"); - }}); - }}; + Map capabilitiesMap + = ImmutableMap.of(CapabilityType.LOGGING_PREFS, ImmutableMap.of("browser", "DEBUG")); DesiredCapabilities caps = new DesiredCapabilities(capabilitiesMap); LoggingPreferences prefs = (LoggingPreferences) caps.getCapability(CapabilityType.LOGGING_PREFS); - assertSame(Level.FINE, prefs.getLevel("browser")); + assertThat(prefs.getLevel("browser")).isSameAs(Level.FINE); } @Test public void shouldAutomaticallyConvertPlatformFromStringToEnum() { DesiredCapabilities caps = new DesiredCapabilities(); caps.setCapability(CapabilityType.PLATFORM, "windows 7"); - assertEquals(caps.getCapability(CapabilityType.PLATFORM), Platform.VISTA); + assertThat(caps.getCapability(CapabilityType.PLATFORM)).isEqualTo(Platform.VISTA); caps.setCapability(CapabilityType.PLATFORM, "WIN8_1"); - assertEquals(caps.getCapability(CapabilityType.PLATFORM), Platform.WIN8_1); + assertThat(caps.getCapability(CapabilityType.PLATFORM)).isEqualTo(Platform.WIN8_1); } @Test public void shouldNotAutomaticallyConvertPlatformIfItNotConvertible() { DesiredCapabilities caps = new DesiredCapabilities(); caps.setCapability(CapabilityType.PLATFORM, "FreeBSD"); - assertEquals(caps.getCapability(CapabilityType.PLATFORM), "FreeBSD"); + assertThat(caps.getCapability(CapabilityType.PLATFORM)).isEqualTo("FreeBSD"); } @Test public void shouldNotAutomaticallyConvertPlatformIfItNotConvertibleInConstructor() { - Map capabilitiesMap = new HashMap() {{ - put(CapabilityType.PLATFORM, "FreeBSD"); - }}; + Map capabilitiesMap = ImmutableMap.of(CapabilityType.PLATFORM, "FreeBSD"); DesiredCapabilities caps = new DesiredCapabilities(capabilitiesMap); - assertEquals(caps.getCapability(CapabilityType.PLATFORM), "FreeBSD"); + assertThat(caps.getCapability(CapabilityType.PLATFORM)).isEqualTo("FreeBSD"); } @Test public void shouldShortenLongValues() { - Map capabilitiesMap = new HashMap() {{ - put("key", createString(1025)); - }}; + Map capabilitiesMap = ImmutableMap.of("key", createString(1025)); DesiredCapabilities caps = new DesiredCapabilities(capabilitiesMap); String expected = "key: " + createString(27) + "..."; - assertTrue(caps.toString(), caps.toString().contains(expected)); + assertThat(caps.toString()).contains(expected); } @Test public void shouldShortenLongEnclosedValues() { - Map capabilitiesMap = new HashMap() {{ - put("key", new HashMap() {{ - put("subkey", createString(1025)); - }}); - }}; + Map capabilitiesMap + = ImmutableMap.of("key", ImmutableMap.of("subkey", createString(1025))); DesiredCapabilities caps = new DesiredCapabilities(capabilitiesMap); String expected = "{subkey: " + createString(27) + "..." + "}"; - assertTrue(caps.toString(), caps.toString().contains(expected)); + assertThat(caps.toString()).contains(expected); } @Test public void canCompareCapabilities() { DesiredCapabilities caps1 = new DesiredCapabilities(); DesiredCapabilities caps2 = new DesiredCapabilities(); - assertEquals(caps1, caps2); + assertThat(caps2).isEqualTo(caps1); caps1.setCapability("xxx", "yyy"); - assertNotEquals(caps1, caps2); + assertThat(caps2).isNotEqualTo(caps1); caps2.setCapability("xxx", "yyy"); - assertEquals(caps1, caps2); + assertThat(caps2).isEqualTo(caps1); } private String createString(int length) { diff --git a/java/client/test/org/openqa/selenium/remote/ErrorHandlerTest.java b/java/client/test/org/openqa/selenium/remote/ErrorHandlerTest.java index 955d96530bd84..3e7202b88ba30 100644 --- a/java/client/test/org/openqa/selenium/remote/ErrorHandlerTest.java +++ b/java/client/test/org/openqa/selenium/remote/ErrorHandlerTest.java @@ -17,23 +17,13 @@ package org.openqa.selenium.remote; -import static java.util.Arrays.asList; -import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.not; -import static org.hamcrest.Matchers.startsWith; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import com.google.common.base.Joiner; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; + import com.google.common.collect.ImmutableMap; import org.junit.Before; import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; import org.openqa.selenium.ElementNotSelectableException; import org.openqa.selenium.ElementNotVisibleException; import org.openqa.selenium.ImeActivationFailedException; @@ -59,17 +49,10 @@ import org.openqa.selenium.interactions.MoveTargetOutOfBoundsException; import org.openqa.selenium.json.Json; +import java.util.Collections; import java.util.HashMap; -import java.util.HashSet; import java.util.Map; -import java.util.Set; - -/** - * Unit tests for {@link ErrorHandler}. - * - * @author jmleyba@gmail.com (Jason Leyba) - */ -@RunWith(JUnit4.class) + public class ErrorHandlerTest { private ErrorHandler handler; @@ -106,113 +89,70 @@ public void testThrowsCorrectExceptionTypes() { InvalidCoordinatesException.class); } - private void assertThrowsCorrectExceptionType( - int status, Class type) { - try { - handler.throwIfResponseFailed(createResponse(status), 123); - fail("Should have a " + type.getName()); - } catch (RuntimeException e) { - assertTrue("Expected:<" + type.getName() + ">, but was:<" + e.getClass().getName() + ">", - type.isAssignableFrom(e.getClass())); - } - } - - private static void assertDoesNotHaveACause(Throwable t) { - if (t.getCause() != null) { - throw new RuntimeException("Should not have a cause", t); - } + private void assertThrowsCorrectExceptionType(int status, Class type) { + assertThatExceptionOfType(RuntimeException.class) + .isThrownBy(() -> handler.throwIfResponseFailed(createResponse(status), 123)) + .satisfies(e -> assertThat(type.isAssignableFrom(e.getClass())).isTrue()); } @SuppressWarnings({"ThrowableInstanceNeverThrown"}) @Test public void testShouldThrowAVanillaWebDriverExceptionIfServerDoesNotProvideAValue() { - try { - Response response = createResponse(ErrorCodes.UNHANDLED_ERROR); - handler.throwIfResponseFailed(response, 123); - fail("Should have thrown!"); - } catch (WebDriverException expected) { - assertDoesNotHaveACause(expected); - String message = expected.getMessage(); - assertThat(message, containsString(new WebDriverException().getMessage())); - assertThat(message, not(containsString("duration"))); // no duration message - } + Response response = createResponse(ErrorCodes.UNHANDLED_ERROR); + assertThatExceptionOfType(WebDriverException.class) + .isThrownBy(() -> handler.throwIfResponseFailed(response, 123)) + .withNoCause() + .withMessageContaining(new WebDriverException().getMessage()); } @SuppressWarnings({"ThrowableInstanceNeverThrown"}) @Test public void testShouldNotSetCauseIfResponseValueIsJustAString() { - try { - handler.throwIfResponseFailed(createResponse(ErrorCodes.UNHANDLED_ERROR, "boom"), 123); - fail("Should have thrown!"); - } catch (WebDriverException expected) { - assertEquals(WebDriverException.class, expected.getClass()); - assertDoesNotHaveACause(expected); - assertThat(expected.getMessage(), containsString("boom")); - assertThat(expected.getMessage(), containsString(new WebDriverException().getMessage())); - } + assertThatExceptionOfType(WebDriverException.class) + .isThrownBy(() -> handler.throwIfResponseFailed( + createResponse(ErrorCodes.UNHANDLED_ERROR, "boom"), 123)) + .withNoCause() + .satisfies(expected -> assertThat(expected).isExactlyInstanceOf(WebDriverException.class)) + .withMessageContaining("boom") + .withMessageContaining(new WebDriverException().getMessage()); } @SuppressWarnings({"ThrowableInstanceNeverThrown"}) @Test public void testCauseShouldBeAnUnknownServerExceptionIfServerOnlyReturnsAMessage() { - try { - handler.throwIfResponseFailed(createResponse(ErrorCodes.UNHANDLED_ERROR, - ImmutableMap.of("message", "boom")), 123); - fail("Should have thrown!"); - } catch (WebDriverException expected) { - assertDoesNotHaveACause(expected); - assertThat(expected.getMessage(), containsString("boom")); - assertThat(expected.getMessage(), containsString(new WebDriverException().getMessage())); - } - } - - private static void assertCauseIsOfType(Class expectedType, Throwable root) { - Throwable cause = root.getCause(); - if (cause == null) { - // Doing it this way makes sure the test logs has the full trace to debug. - throw new RuntimeException("Missing an exception!", root); - } else if (!expectedType.isInstance(cause)) { - throw new RuntimeException("Expected cause to be of type: " + expectedType.getName(), cause); - } + assertThatExceptionOfType(WebDriverException.class) + .isThrownBy(() -> handler.throwIfResponseFailed( + createResponse(ErrorCodes.UNHANDLED_ERROR, ImmutableMap.of("message", "boom")), 123)) + .withNoCause() + .withMessageContaining("boom") + .withMessageContaining(new WebDriverException().getMessage()); } @SuppressWarnings({"ThrowableInstanceNeverThrown"}) @Test public void testCauseShouldUseTheNamedClassIfAvailableOnTheClassPath() { - try { - handler.throwIfResponseFailed(createResponse(ErrorCodes.UNHANDLED_ERROR, - ImmutableMap.of("message", "boom", - "class", NullPointerException.class.getName())), 123); - fail("Should have thrown!"); - } catch (WebDriverException expected) { - assertEquals(new WebDriverException("boom\nCommand duration or timeout: 123 milliseconds").getMessage(), - expected.getMessage()); - - Throwable cause = expected.getCause(); - assertNotNull("Should have a cause", cause); - assertEquals("Wrong cause type", NullPointerException.class, cause.getClass()); - assertEquals("Wrong cause message", "boom", cause.getMessage()); - } + assertThatExceptionOfType(WebDriverException.class) + .isThrownBy(() -> handler.throwIfResponseFailed( + createResponse(ErrorCodes.UNHANDLED_ERROR, + ImmutableMap.of("message", "boom", "class", NullPointerException.class.getName())), 123)) + .withMessage(new WebDriverException("boom\nCommand duration or timeout: 123 milliseconds").getMessage()) + .withCauseInstanceOf(NullPointerException.class) + .satisfies(expected -> assertThat(expected.getCause()).hasMessage("boom")); } @SuppressWarnings({"ThrowableInstanceNeverThrown"}) @Test public void testCauseStackTraceShouldBeEmptyIfTheServerDidNotProvideThatInformation() { - try { - handler.throwIfResponseFailed(createResponse(ErrorCodes.UNHANDLED_ERROR, - ImmutableMap.of("message", "boom", - "class", NullPointerException.class.getName())), 1234); - fail("Should have thrown!"); - } catch (WebDriverException expected) { - assertEquals(new WebDriverException("boom\nCommand duration or timeout: 1.23 seconds").getMessage(), - expected.getMessage()); - - Throwable cause = expected.getCause(); - assertNotNull("Should have a cause", cause); - assertEquals("Wrong cause type", NullPointerException.class, cause.getClass()); - assertEquals("Wrong cause message", "boom", cause.getMessage()); - assertEquals(0, cause.getStackTrace().length); - } + assertThatExceptionOfType(WebDriverException.class) + .isThrownBy(() -> handler.throwIfResponseFailed( + createResponse(ErrorCodes.UNHANDLED_ERROR, + ImmutableMap.of("message", "boom", "class", NullPointerException.class.getName())), 1234)) + .withMessage(new WebDriverException("boom\nCommand duration or timeout: 1.23 seconds").getMessage()) + .withCauseInstanceOf(NullPointerException.class) + .satisfies(expected -> { + assertThat(expected.getCause()).hasMessage("boom"); + assertThat(expected.getCause().getStackTrace()).isEmpty(); + }); } @SuppressWarnings("ThrowableInstanceNeverThrown") @@ -220,23 +160,15 @@ public void testCauseStackTraceShouldBeEmptyIfTheServerDidNotProvideThatInformat public void testShouldBeAbleToRebuildASerializedException() { RuntimeException serverError = new RuntimeException("foo bar baz!\nCommand duration or timeout: 123 milliseconds"); - try { - handler.throwIfResponseFailed( - createResponse(ErrorCodes.UNHANDLED_ERROR, toMap(serverError)), 123); - fail("Should have thrown!"); - } catch (WebDriverException expected) { - WebDriverException webDriverException = new WebDriverException(serverError.getMessage()); - String message = webDriverException.getMessage(); - String message1 = expected.getMessage(); - assertEquals(message, - message1); - - Throwable cause = expected.getCause(); - assertNotNull("Should have a cause", cause); - assertEquals("Wrong cause type", serverError.getClass(), cause.getClass()); - assertEquals("Wrong cause message", serverError.getMessage(), cause.getMessage()); - assertStackTracesEqual(serverError.getStackTrace(), cause.getStackTrace()); - } + assertThatExceptionOfType(WebDriverException.class) + .isThrownBy(()-> handler.throwIfResponseFailed( + createResponse(ErrorCodes.UNHANDLED_ERROR, toMap(serverError)), 123)) + .withMessage(new WebDriverException(serverError.getMessage()).getMessage()) + .withCauseInstanceOf(serverError.getClass()) + .satisfies(expected -> { + assertThat(expected.getCause().getMessage()).isEqualTo(serverError.getMessage()); + assertStackTracesEqual(expected.getCause().getStackTrace(), serverError.getStackTrace()); + }); } @SuppressWarnings("ThrowableInstanceNeverThrown") @@ -246,25 +178,22 @@ public void testShouldIncludeScreenshotIfProvided() { Map data = toMap(serverError); data.put("screen", "screenGrabText"); - try { - handler.throwIfResponseFailed(createResponse(ErrorCodes.UNHANDLED_ERROR, data), 123); - fail("Should have thrown!"); - } catch (WebDriverException expected) { - assertEquals(new WebDriverException(serverError.getMessage() + "\nCommand duration or timeout: 123 milliseconds", - new WebDriverException()).getMessage(), - expected.getMessage()); - - Throwable cause = expected.getCause(); - assertNotNull(cause); - assertEquals(ScreenshotException.class, cause.getClass()); - assertEquals("screenGrabText", ((ScreenshotException) cause).getBase64EncodedScreenshot()); - - Throwable realCause = cause.getCause(); - assertNotNull(realCause); - assertEquals(serverError.getClass(), realCause.getClass()); - assertEquals(serverError.getMessage(), realCause.getMessage()); - assertStackTracesEqual(serverError.getStackTrace(), realCause.getStackTrace()); - } + assertThatExceptionOfType(WebDriverException.class) + .isThrownBy(() -> handler.throwIfResponseFailed( + createResponse(ErrorCodes.UNHANDLED_ERROR, data), 123)) + .withMessage(new WebDriverException( + serverError.getMessage() + "\nCommand duration or timeout: 123 milliseconds", + new WebDriverException()).getMessage()) + .withCauseInstanceOf(ScreenshotException.class) + .satisfies(expected -> { + Throwable cause = expected.getCause(); + assertThat(((ScreenshotException) cause).getBase64EncodedScreenshot()).isEqualTo("screenGrabText"); + Throwable realCause = cause.getCause(); + assertThat(realCause).isNotNull(); + assertThat(realCause.getClass()).isEqualTo(serverError.getClass()); + assertThat(realCause.getMessage()).isEqualTo(serverError.getMessage()); + assertStackTracesEqual(serverError.getStackTrace(), realCause.getStackTrace()); + }); } @SuppressWarnings("ThrowableInstanceNeverThrown") @@ -274,21 +203,18 @@ public void testShouldDefaultToWebDriverExceptionIfClassIsNotSpecified() { Map data = toMap(serverError); data.remove("class"); - try { - handler.throwIfResponseFailed(createResponse(ErrorCodes.UNHANDLED_ERROR, data), 123); - fail("Should have thrown!"); - } catch (WebDriverException expected) { - assertEquals(new WebDriverException(serverError.getMessage() + "\nCommand duration or timeout: 123 milliseconds", - new WebDriverException()).getMessage(), - expected.getMessage()); - - Throwable cause = expected.getCause(); - assertNotNull(cause); - assertEquals(WebDriverException.class, cause.getClass()); - assertEquals(new WebDriverException(serverError.getMessage()).getMessage(), - cause.getMessage()); - assertStackTracesEqual(serverError.getStackTrace(), cause.getStackTrace()); - } + assertThatExceptionOfType(WebDriverException.class) + .isThrownBy(() -> handler.throwIfResponseFailed( + createResponse(ErrorCodes.UNHANDLED_ERROR, data), 123)) + .withMessage(new WebDriverException( + serverError.getMessage() + "\nCommand duration or timeout: 123 milliseconds", + new WebDriverException()).getMessage()) + .withCauseInstanceOf(WebDriverException.class) + .satisfies(expected -> { + Throwable cause = expected.getCause(); + assertThat(cause.getMessage()).isEqualTo(new WebDriverException(serverError.getMessage()).getMessage()); + assertStackTracesEqual(serverError.getStackTrace(), cause.getStackTrace()); + }); } @SuppressWarnings("ThrowableInstanceNeverThrown") @@ -296,34 +222,30 @@ public void testShouldDefaultToWebDriverExceptionIfClassIsNotSpecified() { public void testShouldStillTryToBuildWebDriverExceptionIfClassIsNotProvidedAndStackTraceIsNotForJava() { Map data = ImmutableMap.of( "message", "some error message", - "stackTrace", asList( + "stackTrace", Collections.singletonList( ImmutableMap.of("lineNumber", 1224, - "methodName", "someMethod", - "className", "MyClass", - "fileName", "Resource.m"))); - - try { - handler.throwIfResponseFailed(createResponse(ErrorCodes.UNHANDLED_ERROR, data), 123); - fail("Should have thrown!"); - } catch (WebDriverException expected) { - assertEquals(new WebDriverException("some error message\nCommand duration or timeout: 123 milliseconds", - new WebDriverException()).getMessage(), - expected.getMessage()); - - StackTraceElement[] expectedTrace = { - new StackTraceElement("MyClass", "someMethod", "Resource.m", 1224) - }; - WebDriverException helper = new WebDriverException("some error message"); - helper.setStackTrace(expectedTrace); - - Throwable cause = expected.getCause(); - assertNotNull(cause); - assertEquals(WebDriverException.class, cause.getClass()); - assertEquals(helper.getMessage(), - cause.getMessage()); - - assertStackTracesEqual(expectedTrace, cause.getStackTrace()); - } + "methodName", "someMethod", + "className", "MyClass", + "fileName", "Resource.m"))); + + assertThatExceptionOfType(WebDriverException.class) + .isThrownBy(() -> handler.throwIfResponseFailed( + createResponse(ErrorCodes.UNHANDLED_ERROR, data), 123)) + .withMessage(new WebDriverException( + "some error message\nCommand duration or timeout: 123 milliseconds", + new WebDriverException()).getMessage()) + .withCauseInstanceOf(WebDriverException.class) + .satisfies(expected -> { + StackTraceElement[] expectedTrace = { + new StackTraceElement("MyClass", "someMethod", "Resource.m", 1224) + }; + WebDriverException helper = new WebDriverException("some error message"); + helper.setStackTrace(expectedTrace); + + Throwable cause = expected.getCause(); + assertThat(cause.getMessage()).isEqualTo(helper.getMessage()); + assertStackTracesEqual(expectedTrace, cause.getStackTrace()); + }); } @SuppressWarnings("ThrowableInstanceNeverThrown") @@ -331,34 +253,30 @@ public void testShouldStillTryToBuildWebDriverExceptionIfClassIsNotProvidedAndSt public void testToleratesNonNumericLineNumber() { Map data = ImmutableMap.of( "message", "some error message", - "stackTrace", asList( + "stackTrace", Collections.singletonList( ImmutableMap.of("lineNumber", "some string, might be empty or 'Not avalable'", - "methodName", "someMethod", - "className", "MyClass", - "fileName", "Resource.m"))); - - try { - handler.throwIfResponseFailed(createResponse(ErrorCodes.UNHANDLED_ERROR, data), 123); - fail("Should have thrown!"); - } catch (WebDriverException expected) { - assertEquals(new WebDriverException("some error message\nCommand duration or timeout: 123 milliseconds", - new WebDriverException()).getMessage(), - expected.getMessage()); - - StackTraceElement[] expectedTrace = { - new StackTraceElement("MyClass", "someMethod", "Resource.m", -1) - }; - WebDriverException helper = new WebDriverException("some error message"); - helper.setStackTrace(expectedTrace); - - Throwable cause = expected.getCause(); - assertNotNull(cause); - assertEquals(WebDriverException.class, cause.getClass()); - assertEquals(helper.getMessage(), - cause.getMessage()); - - assertStackTracesEqual(expectedTrace, cause.getStackTrace()); - } + "methodName", "someMethod", + "className", "MyClass", + "fileName", "Resource.m"))); + + assertThatExceptionOfType(WebDriverException.class) + .isThrownBy(() -> handler.throwIfResponseFailed( + createResponse(ErrorCodes.UNHANDLED_ERROR, data), 123)) + .withMessage(new WebDriverException( + "some error message\nCommand duration or timeout: 123 milliseconds", + new WebDriverException()).getMessage()) + .withCauseInstanceOf(WebDriverException.class) + .satisfies(expected -> { + StackTraceElement[] expectedTrace = { + new StackTraceElement("MyClass", "someMethod", "Resource.m", -1) + }; + WebDriverException helper = new WebDriverException("some error message"); + helper.setStackTrace(expectedTrace); + + Throwable cause = expected.getCause(); + assertThat(cause.getMessage()).isEqualTo(helper.getMessage()); + assertStackTracesEqual(expectedTrace, cause.getStackTrace()); + }); } @SuppressWarnings("ThrowableInstanceNeverThrown") @@ -366,34 +284,31 @@ public void testToleratesNonNumericLineNumber() { public void testToleratesNumericLineNumberAsString() { Map data = ImmutableMap.of( "message", "some error message", - "stackTrace", asList( + "stackTrace", Collections.singletonList( ImmutableMap.of("lineNumber", "1224", // number as a string - "methodName", "someMethod", - "className", "MyClass", - "fileName", "Resource.m"))); - - try { - handler.throwIfResponseFailed(createResponse(ErrorCodes.UNHANDLED_ERROR, data), 123); - fail("Should have thrown!"); - } catch (WebDriverException expected) { - assertEquals(new WebDriverException("some error message\nCommand duration or timeout: 123 milliseconds", - new WebDriverException()).getMessage(), - expected.getMessage()); - - StackTraceElement[] expectedTrace = { - new StackTraceElement("MyClass", "someMethod", "Resource.m", 1224) - }; - WebDriverException helper = new WebDriverException("some error message"); - helper.setStackTrace(expectedTrace); - - Throwable cause = expected.getCause(); - assertNotNull(cause); - assertEquals(WebDriverException.class, cause.getClass()); - assertEquals(helper.getMessage(), - cause.getMessage()); - - assertStackTracesEqual(expectedTrace, cause.getStackTrace()); - } + "methodName", "someMethod", + "className", "MyClass", + "fileName", "Resource.m"))); + + assertThatExceptionOfType(WebDriverException.class) + .isThrownBy(() -> handler.throwIfResponseFailed( + createResponse(ErrorCodes.UNHANDLED_ERROR, data), 123)) + .withMessage(new WebDriverException( + "some error message\nCommand duration or timeout: 123 milliseconds", + new WebDriverException()).getMessage()) + .withCauseInstanceOf(WebDriverException.class) + .satisfies(expected -> { + StackTraceElement[] expectedTrace = { + new StackTraceElement("MyClass", "someMethod", "Resource.m", 1224) + }; + WebDriverException helper = new WebDriverException("some error message"); + helper.setStackTrace(expectedTrace); + + Throwable cause = expected.getCause(); + assertThat(cause.getMessage()).isEqualTo(helper.getMessage()); + + assertStackTracesEqual(expectedTrace, cause.getStackTrace()); + }); } @SuppressWarnings("ThrowableInstanceNeverThrown") @@ -403,15 +318,12 @@ public void testShouldIndicateWhenTheServerReturnedAnExceptionThatWasSuppressed( handler.setIncludeServerErrors(false); - try { - handler.throwIfResponseFailed(createResponse( - ErrorCodes.UNHANDLED_ERROR, toMap(serverError)), 123); - fail("Should have thrown!"); - } catch (WebDriverException expected) { - assertDoesNotHaveACause(expected); - assertThat(expected.getMessage(), containsString(serverError.getMessage())); - assertThat(expected.getMessage(), containsString(new WebDriverException().getMessage())); - } + assertThatExceptionOfType(WebDriverException.class) + .isThrownBy(() -> handler.throwIfResponseFailed( + createResponse(ErrorCodes.UNHANDLED_ERROR, toMap(serverError)), 123)) + .withNoCause() + .withMessageContaining(serverError.getMessage()) + .withMessageContaining(new WebDriverException().getMessage()); } @SuppressWarnings("ThrowableInstanceNeverThrown") @@ -423,18 +335,16 @@ public void testShouldStillIncludeScreenshotEvenIfServerSideExceptionsAreDisable handler.setIncludeServerErrors(false); - try { - handler.throwIfResponseFailed(createResponse( - ErrorCodes.UNHANDLED_ERROR, data), 123); - fail("Should have thrown!"); - } catch (WebDriverException expected) { - assertThat(expected.getMessage(), startsWith("foo bar baz!")); - - assertCauseIsOfType(ScreenshotException.class, expected); - ScreenshotException screenshot = (ScreenshotException) expected.getCause(); - assertEquals("screenGrabText", screenshot.getBase64EncodedScreenshot()); - assertDoesNotHaveACause(screenshot); - } + assertThatExceptionOfType(WebDriverException.class) + .isThrownBy(() -> handler.throwIfResponseFailed( + createResponse(ErrorCodes.UNHANDLED_ERROR, data), 123)) + .withMessageStartingWith("foo bar baz!") + .withCauseInstanceOf(ScreenshotException.class) + .satisfies(expected -> { + ScreenshotException screenshot = (ScreenshotException) expected.getCause(); + assertThat(screenshot.getBase64EncodedScreenshot()).isEqualTo("screenGrabText"); + assertThat(screenshot).hasNoCause(); + }); } @Test @@ -467,27 +377,17 @@ public void testStatusCodesRaisedBackToStatusMatches() { exceptions.put(ErrorCodes.INVALID_XPATH_SELECTOR, InvalidSelectorException.class); exceptions.put(ErrorCodes.INVALID_XPATH_SELECTOR_RETURN_TYPER, InvalidSelectorException.class); - Set collectedFailures = new HashSet<>(); for (Map.Entry> exception : exceptions.entrySet()) { - try { - handler.throwIfResponseFailed(createResponse(exception.getKey()), 123); - fail("Should have thrown an Exception"); - } catch (Exception e) { - assertEquals("Checking status code: " + exception.getKey(), exception.getValue().getSimpleName(), e.getClass().getSimpleName()); - - int expected = exception.getKey(); - if (e instanceof InvalidSelectorException) { - // all of the special invalid selector exceptions are just mapped to the generic invalid selector - expected = ErrorCodes.INVALID_SELECTOR_ERROR; - } - int seenStatusCode = new ErrorCodes().toStatusCode(e); - if (seenStatusCode != expected) { - collectedFailures.add(String.format("%s: ErrorCode.toStatusCode. Expected %d, saw %d", e.getClass().getSimpleName(), expected, seenStatusCode)); - } - } - } - if (!collectedFailures.isEmpty()) { - fail(Joiner.on("\n").join(collectedFailures)); + assertThatExceptionOfType(WebDriverException.class) + .isThrownBy(() -> handler.throwIfResponseFailed(createResponse(exception.getKey()), 123)) + .satisfies(e -> { + assertThat(e.getClass().getSimpleName()).isEqualTo(exception.getValue().getSimpleName()); + + // all of the special invalid selector exceptions are just mapped to the generic invalid selector + int expected = e instanceof InvalidSelectorException + ? ErrorCodes.INVALID_SELECTOR_ERROR : exception.getKey(); + assertThat(new ErrorCodes().toStatusCode(e)).isEqualTo(expected); + }); } } @@ -502,17 +402,14 @@ private Response createResponse(int status, Object value) { return response; } - private static void assertStackTracesEqual(StackTraceElement[] expected, - StackTraceElement[] actual) { - assertEquals("Stack traces have different sizes", expected.length, actual.length); + private static void assertStackTracesEqual(StackTraceElement[] expected, StackTraceElement[] actual) { + assertThat(actual.length).as("Stacktrace length").isEqualTo(expected.length); for (int i = 0; i < expected.length; i++) { - String message = "Frames differ at index [" + i + "]; expected:<" - + expected[i] + "> but was:<" + actual[i] + ">"; - - assertEquals(message, expected[i].getFileName(), actual[i].getFileName()); - assertEquals(message, expected[i].getClassName(), actual[i].getClassName()); - assertEquals(message, expected[i].getMethodName(), actual[i].getMethodName()); - assertEquals(message, expected[i].getLineNumber(), actual[i].getLineNumber()); + String message = "Frames at index [" + i + "]"; + assertThat(actual[i].getFileName()).as(message).isEqualTo(expected[i].getFileName()); + assertThat(actual[i].getClassName()).as(message).isEqualTo(expected[i].getClassName()); + assertThat(actual[i].getMethodName()).as(message).isEqualTo(expected[i].getMethodName()); + assertThat(actual[i].getLineNumber()).as(message).isEqualTo(expected[i].getLineNumber()); } } diff --git a/java/client/test/org/openqa/selenium/remote/JdkAugmenterTest.java b/java/client/test/org/openqa/selenium/remote/JdkAugmenterTest.java index 216054b20f561..0246d8b562165 100644 --- a/java/client/test/org/openqa/selenium/remote/JdkAugmenterTest.java +++ b/java/client/test/org/openqa/selenium/remote/JdkAugmenterTest.java @@ -17,10 +17,6 @@ package org.openqa.selenium.remote; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -@RunWith(JUnit4.class) public class JdkAugmenterTest extends BaseAugmenterTest { @Override diff --git a/java/client/test/org/openqa/selenium/remote/JsonWireProtocolResponseTest.java b/java/client/test/org/openqa/selenium/remote/JsonWireProtocolResponseTest.java index b2b480a135964..35f7fda8dfa8c 100644 --- a/java/client/test/org/openqa/selenium/remote/JsonWireProtocolResponseTest.java +++ b/java/client/test/org/openqa/selenium/remote/JsonWireProtocolResponseTest.java @@ -18,10 +18,8 @@ package org.openqa.selenium.remote; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import com.google.common.collect.ImmutableMap; import com.google.gson.Gson; @@ -54,16 +52,16 @@ public void successfulResponseGetsParsedProperly() { Optional optionalResult = new JsonWireProtocolResponse().getResponseFunction().apply(initialResponse); - assertTrue(optionalResult.isPresent()); + assertThat(optionalResult.isPresent()).isTrue(); ProtocolHandshake.Result result = optionalResult.get(); - assertEquals(Dialect.OSS, result.getDialect()); + assertThat(result.getDialect()).isEqualTo(Dialect.OSS); Response response = result.createResponse(); - assertEquals("success", response.getState()); - assertEquals(0, (int) response.getStatus()); + assertThat(response.getState()).isEqualTo("success"); + assertThat((int) response.getStatus()).isEqualTo(0); - assertEquals(caps.asMap(), response.getValue()); + assertThat(response.getValue()).isEqualTo(caps.asMap()); } @Test @@ -82,7 +80,7 @@ public void shouldIgnoreAw3CProtocolReply() { Optional optionalResult = new JsonWireProtocolResponse().getResponseFunction().apply(initialResponse); - assertFalse(optionalResult.isPresent()); + assertThat(optionalResult.isPresent()).isFalse(); } @Test @@ -100,7 +98,7 @@ public void shouldIgnoreAGeckodriver013Reply() { Optional optionalResult = new JsonWireProtocolResponse().getResponseFunction().apply(initialResponse); - assertFalse(optionalResult.isPresent()); + assertThat(optionalResult.isPresent()).isFalse(); } @Test @@ -116,13 +114,8 @@ public void shouldProperlyPopulateAnError() { 500, payload); - - try { - new JsonWireProtocolResponse().getResponseFunction().apply(initialResponse); - fail(); - } catch (SessionNotCreatedException e) { - assertTrue(e.getMessage().contains("me no likey")); - } - + assertThatExceptionOfType(SessionNotCreatedException.class) + .isThrownBy(() -> new JsonWireProtocolResponse().getResponseFunction().apply(initialResponse)) + .withMessageContaining("me no likey"); } } diff --git a/java/client/test/org/openqa/selenium/remote/ProtocolHandshakeTest.java b/java/client/test/org/openqa/selenium/remote/ProtocolHandshakeTest.java index 93139bbbb3f01..db93e56692424 100644 --- a/java/client/test/org/openqa/selenium/remote/ProtocolHandshakeTest.java +++ b/java/client/test/org/openqa/selenium/remote/ProtocolHandshakeTest.java @@ -19,16 +19,7 @@ import static java.net.HttpURLConnection.HTTP_OK; import static java.nio.charset.StandardCharsets.UTF_8; -import static org.hamcrest.Matchers.allOf; -import static org.hamcrest.Matchers.contains; -import static org.hamcrest.Matchers.containsInAnyOrder; -import static org.hamcrest.Matchers.hasEntry; -import static org.hamcrest.Matchers.hasKey; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.openqa.selenium.Proxy.ProxyType.AUTODETECT; import com.google.common.collect.ImmutableList; @@ -46,7 +37,7 @@ import java.io.IOException; import java.util.Collection; -import java.util.HashSet; +import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Set; @@ -70,7 +61,7 @@ public void requestShouldIncludeJsonWireProtocolCapabilities() throws IOExceptio Map json = getRequestPayloadAsMap(client); - assertEquals(ImmutableMap.of(), json.get("desiredCapabilities")); + assertThat(json.get("desiredCapabilities")).isEqualTo(Collections.EMPTY_MAP); } @Test @@ -90,7 +81,7 @@ public void requestShouldIncludeSpecCompliantW3CCapabilities() throws IOExceptio List> caps = mergeW3C(json); - assertFalse(caps.isEmpty()); + assertThat(caps).isNotEmpty(); } @Test @@ -105,7 +96,7 @@ public void shouldParseW3CNewSessionResponse() throws IOException { RecordingHttpClient client = new RecordingHttpClient(response); ProtocolHandshake.Result result = new ProtocolHandshake().createSession(client, command); - assertEquals(result.getDialect(), Dialect.W3C); + assertThat(result.getDialect()).isEqualTo(Dialect.W3C); } @Test @@ -120,7 +111,7 @@ public void shouldParseWireProtocolNewSessionResponse() throws IOException { RecordingHttpClient client = new RecordingHttpClient(response); ProtocolHandshake.Result result = new ProtocolHandshake().createSession(client, command); - assertEquals(result.getDialect(), Dialect.OSS); + assertThat(result.getDialect()).isEqualTo(Dialect.OSS); } @Test @@ -144,23 +135,21 @@ public void shouldNotIncludeNonProtocolExtensionKeys() throws IOException { Map handshakeRequest = getRequestPayloadAsMap(client); Object rawCaps = handshakeRequest.get("capabilities"); - assertTrue(rawCaps instanceof Map); + assertThat(rawCaps).isInstanceOf(Map.class); Map capabilities = (Map) rawCaps; - assertNull(capabilities.get("alwaysMatch")); + assertThat(capabilities.get("alwaysMatch")).isNull(); List> first = (List>) capabilities.get("firstMatch"); // We don't care where they are, but we want to see "se:option" and not "option" - Set keys = new HashSet<>(); - keys.addAll(first.stream() - .map(Map::keySet) - .flatMap(Collection::stream) - .map(String::valueOf) - .collect(Collectors.toSet())); - assertTrue(keys.contains("browserName")); - assertTrue(keys.contains("se:option")); - assertFalse(keys.contains("options")); + Set keys = first.stream() + .map(Map::keySet) + .flatMap(Collection::stream) + .map(String::valueOf).collect(Collectors.toSet()); + assertThat(keys) + .contains("browserName", "se:option") + .doesNotContain("options"); } @Test @@ -184,16 +173,16 @@ public void firstMatchSeparatesCapsForDifferentBrowsers() throws IOException { List> capabilities = mergeW3C(handshakeRequest); - assertThat(capabilities, containsInAnyOrder( - ImmutableMap.of("moz:firefoxOptions", ImmutableMap.of()), - ImmutableMap.of("browserName", "chrome"))); + assertThat(capabilities).contains( + ImmutableMap.of("moz:firefoxOptions", Collections.EMPTY_MAP), + ImmutableMap.of("browserName", "chrome")); } @Test public void doesNotCreateFirstMatchForNonW3CCaps() throws IOException { Capabilities caps = new ImmutableCapabilities( - "cheese", ImmutableMap.of(), - "moz:firefoxOptions", ImmutableMap.of(), + "cheese", Collections.EMPTY_MAP, + "moz:firefoxOptions", Collections.EMPTY_MAP, "browserName", "firefox"); Map params = ImmutableMap.of("desiredCapabilities", caps); @@ -211,13 +200,14 @@ public void doesNotCreateFirstMatchForNonW3CCaps() throws IOException { List> w3c = mergeW3C(handshakeRequest); - assertEquals(1, w3c.size()); + assertThat(w3c).hasSize(1); // firstMatch should not contain an object for Chrome-specific capabilities. Because // "chromeOptions" is not a W3C capability name, it is stripped from any firstMatch objects. // The resulting empty object should be omitted from firstMatch; if it is present, then the // Firefox-specific capabilities might be ignored. - assertThat(w3c, contains( - allOf(hasKey("moz:firefoxOptions"), hasEntry("browserName", "firefox")))); + assertThat(w3c.get(0)) + .containsKey("moz:firefoxOptions") + .containsEntry("browserName", "firefox"); } @Test @@ -240,12 +230,12 @@ public void shouldLowerCaseProxyTypeForW3CRequest() throws IOException { mergeW3C(handshakeRequest).forEach(always -> { Map seenProxy = (Map) always.get("proxy"); - assertEquals("autodetect", seenProxy.get("proxyType")); + assertThat(seenProxy.get("proxyType")).isEqualTo("autodetect"); }); Map jsonCaps = (Map) handshakeRequest.get("desiredCapabilities"); Map seenProxy = (Map) jsonCaps.get("proxy"); - assertEquals("AUTODETECT", seenProxy.get("proxyType")); + assertThat(seenProxy.get("proxyType")).isEqualTo("AUTODETECT"); } @Test @@ -270,9 +260,9 @@ public void shouldNotIncludeMappingOfANYPlatform() throws IOException { mergeW3C(handshakeRequest) .forEach(capabilities -> { - assertEquals("cake", capabilities.get("browserName")); - assertNull(capabilities.toString(), capabilities.get("platformName")); - assertNull(capabilities.toString(), capabilities.get("platform")); + assertThat(capabilities.get("browserName")).isEqualTo("cake"); + assertThat(capabilities.get("platformName")).isNull(); + assertThat(capabilities.get("platform")).isNull(); }); } @@ -294,7 +284,7 @@ private List> mergeW3C(Map caps) { .map(first -> ImmutableMap.builder().putAll(always).putAll(first).build()) .collect(Collectors.toList()); - assertFalse("Unable to construct valid capabilities", allCaps.isEmpty()); + assertThat(allCaps).isNotEmpty(); return allCaps; } diff --git a/java/client/test/org/openqa/selenium/remote/RemoteLogsTest.java b/java/client/test/org/openqa/selenium/remote/RemoteLogsTest.java index 029d3b26281f5..87f1594ab5769 100644 --- a/java/client/test/org/openqa/selenium/remote/RemoteLogsTest.java +++ b/java/client/test/org/openqa/selenium/remote/RemoteLogsTest.java @@ -17,19 +17,16 @@ package org.openqa.selenium.remote; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; -import org.hamcrest.CoreMatchers; import org.junit.Before; import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.openqa.selenium.WebDriverException; @@ -37,7 +34,6 @@ import org.openqa.selenium.logging.LogEntries; import org.openqa.selenium.logging.LogEntry; import org.openqa.selenium.logging.LogType; -import org.openqa.selenium.testing.TestUtilities; import java.util.ArrayList; import java.util.HashSet; @@ -45,7 +41,6 @@ import java.util.Set; import java.util.logging.Level; -@RunWith(JUnit4.class) public class RemoteLogsTest { @Mock private ExecuteMethod executeMethod; @@ -75,9 +70,9 @@ public void canGetProfilerLogs() { LogEntries logEntries = remoteLogs.get(LogType.PROFILER); List allLogEntries = logEntries.getAll(); - assertEquals(2, allLogEntries.size()); - assertEquals("hello", allLogEntries.get(0).getMessage()); - assertEquals("world", allLogEntries.get(1).getMessage()); + assertThat(allLogEntries).hasSize(2); + assertThat(allLogEntries.get(0).getMessage()).isEqualTo("hello"); + assertThat(allLogEntries.get(1).getMessage()).isEqualTo("world"); } @Test @@ -94,8 +89,8 @@ public void canGetLocalProfilerLogsIfNoRemoteProfilerLogSupport() { LogEntries logEntries = remoteLogs.get(LogType.PROFILER); List allLogEntries = logEntries.getAll(); - assertEquals(1, allLogEntries.size()); - assertEquals("hello", allLogEntries.get(0).getMessage()); + assertThat(allLogEntries).hasSize(1); + assertThat(allLogEntries.get(0).getMessage()).isEqualTo("hello"); } @Test @@ -105,8 +100,8 @@ public void canGetClientLogs() { when(localLogs.get(LogType.CLIENT)).thenReturn(new LogEntries(entries)); LogEntries logEntries = remoteLogs.get(LogType.CLIENT); - assertEquals(1, logEntries.getAll().size()); - assertEquals("hello", logEntries.getAll().get(0).getMessage()); + assertThat(logEntries.getAll()).hasSize(1); + assertThat(logEntries.getAll().get(0).getMessage()).isEqualTo("hello"); // Client logs should not retrieve remote logs. verifyNoMoreInteractions(executeMethod); @@ -121,8 +116,8 @@ public void canGetServerLogs() { ImmutableMap.of("level", Level.INFO.getName(), "timestamp", 0L, "message", "world"))); LogEntries logEntries = remoteLogs.get(LogType.SERVER); - assertEquals(1, logEntries.getAll().size()); - assertEquals("world", logEntries.getAll().get(0).getMessage()); + assertThat(logEntries.getAll()).hasSize(1); + assertThat(logEntries.getAll().get(0).getMessage()).isEqualTo("world"); // Server logs should not retrieve local logs. verifyNoMoreInteractions(localLogs); @@ -138,8 +133,8 @@ public void throwsOnBogusRemoteLogsResponse() { .put("message", "Command not found: POST /session/11037/log") .put("stacktrace", "").build()); - Throwable ex = TestUtilities.catchThrowable(() -> remoteLogs.get(LogType.BROWSER)); - assertThat(ex, CoreMatchers.instanceOf(WebDriverException.class)); + assertThatExceptionOfType(WebDriverException.class) + .isThrownBy(() -> remoteLogs.get(LogType.BROWSER)); verifyNoMoreInteractions(localLogs); } @@ -166,6 +161,6 @@ public void canGetAvailableLogTypes() { Set availableLogTypes = remoteLogs.getAvailableLogTypes(); - assertEquals(expected, availableLogTypes); + assertThat(availableLogTypes).isEqualTo(expected); } } diff --git a/java/client/test/org/openqa/selenium/remote/RemoteWebDriverInitializationTest.java b/java/client/test/org/openqa/selenium/remote/RemoteWebDriverInitializationTest.java index dbd98c6d171d0..d7d33300b4d30 100644 --- a/java/client/test/org/openqa/selenium/remote/RemoteWebDriverInitializationTest.java +++ b/java/client/test/org/openqa/selenium/remote/RemoteWebDriverInitializationTest.java @@ -17,11 +17,8 @@ package org.openqa.selenium.remote; -import static org.hamcrest.CoreMatchers.containsString; -import static org.hamcrest.CoreMatchers.equalTo; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.mockito.Mockito.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -29,28 +26,22 @@ import com.google.common.collect.ImmutableMap; import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; import org.openqa.selenium.Capabilities; import org.openqa.selenium.ImmutableCapabilities; import org.openqa.selenium.Platform; -import org.openqa.selenium.testing.TestUtilities; import java.io.IOException; -@RunWith(JUnit4.class) public class RemoteWebDriverInitializationTest { private boolean quitCalled = false; @Test public void testQuitsIfStartSessionFails() { - Throwable ex = TestUtilities.catchThrowable( - () -> new BadStartSessionRemoteWebDriver(mock(CommandExecutor.class), - new ImmutableCapabilities())); + assertThatExceptionOfType(RuntimeException.class) + .isThrownBy(() -> new BadStartSessionRemoteWebDriver(mock(CommandExecutor.class), new ImmutableCapabilities())) + .withMessageContaining("Stub session that should fail"); - assertNotNull(ex); - assertThat(ex.getMessage(), containsString("Stub session that should fail")); - assertTrue(quitCalled); + assertThat(quitCalled).isTrue(); } @Test @@ -60,7 +51,7 @@ public void canHandleNonStandardCapabilitiesReturnedByRemoteEnd() throws IOExcep CommandExecutor executor = mock(CommandExecutor.class); when(executor.execute(any())).thenReturn(resp); RemoteWebDriver driver = new RemoteWebDriver(executor, new ImmutableCapabilities()); - assertThat(driver.getCapabilities().getCapability("platform"), equalTo(Platform.UNIX)); + assertThat(driver.getCapabilities().getCapability("platform")).isEqualTo(Platform.UNIX); } private class BadStartSessionRemoteWebDriver extends RemoteWebDriver { diff --git a/java/client/test/org/openqa/selenium/remote/RemoteWebDriverScreenshotTest.java b/java/client/test/org/openqa/selenium/remote/RemoteWebDriverScreenshotTest.java index ef355abf119b7..d13f3dbd92d13 100644 --- a/java/client/test/org/openqa/selenium/remote/RemoteWebDriverScreenshotTest.java +++ b/java/client/test/org/openqa/selenium/remote/RemoteWebDriverScreenshotTest.java @@ -17,9 +17,8 @@ package org.openqa.selenium.remote; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.openqa.selenium.OutputType.BASE64; import static org.openqa.selenium.testing.Driver.GRID; import static org.openqa.selenium.testing.Driver.HTMLUNIT; @@ -48,12 +47,10 @@ public void testShouldBeAbleToGrabASnapshotOnException() { driver.get(pages.simpleTestPage); - try { - driver.findElement(By.id("doesnayexist")); - fail(); - } catch (NoSuchElementException e) { - assertTrue(((ScreenshotException) e.getCause()).getBase64EncodedScreenshot().length() > 0); - } + assertThatExceptionOfType(NoSuchElementException.class) + .isThrownBy(() -> driver.findElement(By.id("doesnayexist"))) + .satisfies(e -> assertThat( + ((ScreenshotException) e.getCause()).getBase64EncodedScreenshot().length()).isGreaterThan(0)); } @Test @@ -74,7 +71,7 @@ public void testCanAugmentWebDriverInstanceIfNecessary() { WebDriver toUse = new Augmenter().augment(driver); String screenshot = ((TakesScreenshot) toUse).getScreenshotAs(BASE64); - assertTrue(screenshot.length() > 0); + assertThat(screenshot.length()).isGreaterThan(0); } @Test @@ -90,16 +87,15 @@ public void testShouldBeAbleToDisableSnapshotOnException() { noScreenshotDriver.get(pages.simpleTestPage); - try { - noScreenshotDriver.findElement(By.id("doesnayexist")); - fail(); - } catch (NoSuchElementException e) { - Throwable t = e; - while (t != null) { - assertFalse(t instanceof ScreenshotException); - t = t.getCause(); - } - } + assertThatExceptionOfType(NoSuchElementException.class) + .isThrownBy(() -> noScreenshotDriver.findElement(By.id("doesnayexist"))) + .satisfies(e -> { + Throwable t = e; + while (t != null) { + assertThat(t).isNotInstanceOf(ScreenshotException.class); + t = t.getCause(); + } + }); } } diff --git a/java/client/test/org/openqa/selenium/remote/StartingFirefoxRemotelyTest.java b/java/client/test/org/openqa/selenium/remote/StartingFirefoxRemotelyTest.java index 252caadc9c3b1..96574eeb45e94 100644 --- a/java/client/test/org/openqa/selenium/remote/StartingFirefoxRemotelyTest.java +++ b/java/client/test/org/openqa/selenium/remote/StartingFirefoxRemotelyTest.java @@ -17,7 +17,7 @@ package org.openqa.selenium.remote; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import org.junit.After; import org.junit.Assume; @@ -68,7 +68,7 @@ public void canSetProfileThroughDesiredCapabilities() { localDriver = new RemoteWebDriver(remoteUrl, caps); localDriver.get(pages.xhtmlTestPage); - assertEquals("XHTML Test Page", localDriver.getTitle()); + assertThat(localDriver.getTitle()).isEqualTo("XHTML Test Page"); } @Test @@ -79,7 +79,7 @@ public void canSetProfileThroughFirefoxOptions() { localDriver = new RemoteWebDriver(remoteUrl, caps); localDriver.get(pages.xhtmlTestPage); - assertEquals("XHTML Test Page", localDriver.getTitle()); + assertThat(localDriver.getTitle()).isEqualTo("XHTML Test Page"); } @Test @@ -88,13 +88,13 @@ public void shouldBeAbleToMergeDesiredOptionsIntoFirefoxOptions() { localDriver = new RemoteWebDriver(remoteUrl, options); localDriver.get(pages.xhtmlTestPage); - assertEquals("XHTML Test Page", localDriver.getTitle()); + assertThat(localDriver.getTitle()).isEqualTo("XHTML Test Page"); } @Test public void canStartFirefoxWithoutAnyConfigurationOptions() { localDriver = new RemoteWebDriver(remoteUrl, new FirefoxOptions()); localDriver.get(pages.xhtmlTestPage); - assertEquals("XHTML Test Page", localDriver.getTitle()); + assertThat(localDriver.getTitle()).isEqualTo("XHTML Test Page"); } } diff --git a/java/client/test/org/openqa/selenium/remote/W3CHandshakeResponseTest.java b/java/client/test/org/openqa/selenium/remote/W3CHandshakeResponseTest.java index bf7b4cccb8e4b..c74c7bf657e8c 100644 --- a/java/client/test/org/openqa/selenium/remote/W3CHandshakeResponseTest.java +++ b/java/client/test/org/openqa/selenium/remote/W3CHandshakeResponseTest.java @@ -17,10 +17,8 @@ package org.openqa.selenium.remote; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import com.google.common.collect.ImmutableMap; @@ -49,16 +47,16 @@ public void successfulResponseGetsParsedProperly() { Optional optionalResult = new W3CHandshakeResponse().getResponseFunction().apply(initialResponse); - assertTrue(optionalResult.isPresent()); + assertThat(optionalResult.isPresent()).isTrue(); ProtocolHandshake.Result result = optionalResult.get(); - assertEquals(Dialect.W3C, result.getDialect()); + assertThat(result.getDialect()).isEqualTo(Dialect.W3C); Response response = result.createResponse(); - assertEquals("success", response.getState()); - assertEquals(0, (int) response.getStatus()); + assertThat(response.getState()).isEqualTo("success"); + assertThat((int) response.getStatus()).isEqualTo(0); - assertEquals(caps.asMap(), response.getValue()); + assertThat(response.getValue()).isEqualTo(caps.asMap()); } @Test @@ -77,7 +75,7 @@ public void shouldIgnoreAJsonWireProtocolReply() { Optional optionalResult = new W3CHandshakeResponse().getResponseFunction().apply(initialResponse); - assertFalse(optionalResult.isPresent()); + assertThat(optionalResult.isPresent()).isFalse(); } @Test @@ -95,7 +93,7 @@ public void shouldIgnoreAGeckodriver013Reply() { Optional optionalResult = new W3CHandshakeResponse().getResponseFunction().apply(initialResponse); - assertFalse(optionalResult.isPresent()); + assertThat(optionalResult.isPresent()).isFalse(); } @Test @@ -112,13 +110,9 @@ public void shouldProperlyPopulateAnError() { payload); - try { - new W3CHandshakeResponse().getResponseFunction().apply(initialResponse); - fail(); - } catch (SessionNotCreatedException e) { - assertTrue(e.getMessage().contains("me no likey")); - assertTrue(e.getAdditionalInformation().contains("I have no idea what went wrong")); - } - + assertThatExceptionOfType(SessionNotCreatedException.class) + .isThrownBy(() -> new W3CHandshakeResponse().getResponseFunction().apply(initialResponse)) + .withMessageContaining("me no likey") + .satisfies(e -> assertThat(e.getAdditionalInformation()).contains("I have no idea what went wrong")); } } diff --git a/java/client/test/org/openqa/selenium/remote/http/JsonHttpCommandCodecTest.java b/java/client/test/org/openqa/selenium/remote/http/JsonHttpCommandCodecTest.java index 35289ba7e483d..ec4e32ede9909 100644 --- a/java/client/test/org/openqa/selenium/remote/http/JsonHttpCommandCodecTest.java +++ b/java/client/test/org/openqa/selenium/remote/http/JsonHttpCommandCodecTest.java @@ -23,13 +23,8 @@ import static com.google.common.net.MediaType.JSON_UTF_8; import static java.nio.charset.StandardCharsets.UTF_16; import static java.nio.charset.StandardCharsets.UTF_8; -import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.nullValue; -import static org.hamcrest.Matchers.startsWith; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.openqa.selenium.remote.Dialect.OSS; import static org.openqa.selenium.remote.http.HttpMethod.DELETE; import static org.openqa.selenium.remote.http.HttpMethod.GET; @@ -41,8 +36,6 @@ import com.google.gson.JsonObject; import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; import org.openqa.selenium.UnsupportedCommandException; import org.openqa.selenium.remote.Command; import org.openqa.selenium.remote.DriverCommand; @@ -52,7 +45,6 @@ import java.util.Map; -@RunWith(JUnit4.class) public class JsonHttpCommandCodecTest { private final JsonHttpCommandCodec codec = new JsonHttpCommandCodec(); @@ -60,36 +52,27 @@ public class JsonHttpCommandCodecTest { @Test public void throwsIfCommandNameIsNotRecognized() { Command command = new Command(null, "garbage-command-name"); - try { - codec.encode(command); - fail(); - } catch (UnsupportedCommandException expected) { - assertThat(expected.getMessage(), startsWith(command.getName() + "\n")); - } + assertThatExceptionOfType(UnsupportedCommandException.class) + .isThrownBy(() -> codec.encode(command)) + .withMessageStartingWith(command.getName() + "\n"); } @Test public void throwsIfCommandHasNullSessionId() { codec.defineCommand("foo", DELETE, "/foo/:sessionId"); Command command = new Command(null, "foo"); - try { - codec.encode(command); - fail(); - } catch (IllegalArgumentException expected) { - assertThat(expected.getMessage(), containsString("Session ID")); - } + assertThatExceptionOfType(IllegalArgumentException.class) + .isThrownBy(() -> codec.encode(command)) + .withMessageContaining("Session ID"); } @Test public void throwsIfCommandIsMissingUriParameter() { codec.defineCommand("foo", DELETE, "/foo/:bar"); Command command = new Command(new SessionId("id"), "foo"); - try { - codec.encode(command); - fail(); - } catch (IllegalArgumentException expected) { - assertThat(expected.getMessage(), containsString("bar")); - } + assertThatExceptionOfType(IllegalArgumentException.class) + .isThrownBy(() -> codec.encode(command)) + .withMessageContaining("bar"); } @Test @@ -98,11 +81,11 @@ public void encodingAPostWithNoParameters() { Command command = new Command(null, "foo"); HttpRequest request = codec.encode(command); - assertThat(request.getMethod(), is(POST)); - assertThat(request.getHeader(CONTENT_TYPE), is(JSON_UTF_8.toString())); - assertThat(request.getHeader(CONTENT_LENGTH), is("3")); - assertThat(request.getUri(), is("/foo/bar")); - assertThat(new String(request.getContent(), UTF_8), is("{\n}")); + assertThat(request.getMethod()).isEqualTo(POST); + assertThat(request.getHeader(CONTENT_TYPE)).isEqualTo(JSON_UTF_8.toString()); + assertThat(request.getHeader(CONTENT_LENGTH)).isEqualTo("3"); + assertThat(request.getUri()).isEqualTo("/foo/bar"); + assertThat(new String(request.getContent(), UTF_8)).isEqualTo("{\n}"); } @Test @@ -113,22 +96,22 @@ public void encodingAPostWithUrlParameters() { String encoding = "{\n \"bar\": \"apples123\"\n}"; HttpRequest request = codec.encode(command); - assertThat(request.getMethod(), is(POST)); - assertThat(request.getHeader(CONTENT_TYPE), is(JSON_UTF_8.toString())); - assertThat(request.getHeader(CONTENT_LENGTH), is(String.valueOf(encoding.length()))); - assertThat(request.getUri(), is("/foo/apples123/baz")); - assertThat(new String(request.getContent(), UTF_8), is(encoding)); + assertThat(request.getMethod()).isEqualTo(POST); + assertThat(request.getHeader(CONTENT_TYPE)).isEqualTo(JSON_UTF_8.toString()); + assertThat(request.getHeader(CONTENT_LENGTH)).isEqualTo(String.valueOf(encoding.length())); + assertThat(request.getUri()).isEqualTo("/foo/apples123/baz"); + assertThat(new String(request.getContent(), UTF_8)).isEqualTo(encoding); } @Test public void encodingANonPostWithNoParameters() { codec.defineCommand("foo", DELETE, "/foo/bar/baz"); HttpRequest request = codec.encode(new Command(null, "foo")); - assertThat(request.getMethod(), is(DELETE)); - assertThat(request.getHeader(CONTENT_TYPE), is(nullValue())); - assertThat(request.getHeader(CONTENT_LENGTH), is(nullValue())); - assertThat(request.getContent().length, is(0)); - assertThat(request.getUri(), is("/foo/bar/baz")); + assertThat(request.getMethod()).isEqualTo(DELETE); + assertThat(request.getHeader(CONTENT_TYPE)).isNull(); + assertThat(request.getHeader(CONTENT_LENGTH)).isNull(); + assertThat(request.getContent().length).isEqualTo(0); + assertThat(request.getUri()).isEqualTo("/foo/bar/baz"); } @Test @@ -136,29 +119,26 @@ public void encodingANonPostWithParameters() { codec.defineCommand("eat", GET, "/fruit/:fruit/:size"); HttpRequest request = codec.encode(new Command(null, "eat", ImmutableMap.of( "fruit", "apple", "size", "large"))); - assertThat(request.getHeader(CONTENT_TYPE), is(nullValue())); - assertThat(request.getHeader(CONTENT_LENGTH), is(nullValue())); - assertThat(request.getContent().length, is(0)); - assertThat(request.getUri(), is("/fruit/apple/large")); + assertThat(request.getHeader(CONTENT_TYPE)).isNull(); + assertThat(request.getHeader(CONTENT_LENGTH)).isNull(); + assertThat(request.getContent().length).isEqualTo(0); + assertThat(request.getUri()).isEqualTo("/fruit/apple/large"); } @Test public void preventsCachingGetRequests() { codec.defineCommand("foo", GET, "/foo"); HttpRequest request = codec.encode(new Command(null, "foo")); - assertThat(request.getMethod(), is(GET)); - assertThat(request.getHeader(CACHE_CONTROL), is("no-cache")); + assertThat(request.getMethod()).isEqualTo(GET); + assertThat(request.getHeader(CACHE_CONTROL)).isEqualTo("no-cache"); } @Test public void throwsIfEncodedCommandHasNoMapping() { HttpRequest request = new HttpRequest(GET, "/foo/bar/baz"); - try { - codec.decode(request); - fail(); - } catch (UnsupportedCommandException expected) { - assertThat(expected.getMessage(), startsWith("GET /foo/bar/baz\n")); - } + assertThatExceptionOfType(UnsupportedCommandException.class) + .isThrownBy(() -> codec.decode(request)) + .withMessageStartingWith("GET /foo/bar/baz\n"); } @Test @@ -167,9 +147,9 @@ public void canDecodeCommandWithNoParameters() { codec.defineCommand("foo", GET, "/foo/bar/baz"); Command decoded = codec.decode(request); - assertThat(decoded.getName(), is("foo")); - assertThat(decoded.getSessionId(), is(nullValue())); - assertThat(decoded.getParameters().isEmpty(), is(true)); + assertThat(decoded.getName()).isEqualTo("foo"); + assertThat(decoded.getSessionId()).isNull(); + assertThat(decoded.getParameters()).isEmpty(); } @Test @@ -178,7 +158,7 @@ public void canExtractSessionIdFromPathParameters() { codec.defineCommand("foo", GET, "/foo/:sessionId/baz"); Command decoded = codec.decode(request); - assertThat(decoded.getSessionId(), is(new SessionId("bar"))); + assertThat(decoded.getSessionId()).isEqualTo(new SessionId("bar")); } @Test @@ -187,8 +167,8 @@ public void removesSessionIdFromParameterMap() { codec.defineCommand("foo", GET, "/foo/:sessionId/baz"); Command decoded = codec.decode(request); - assertThat(decoded.getSessionId(), is(new SessionId("bar"))); - assertThat(decoded.getParameters().isEmpty(), is(true)); + assertThat(decoded.getSessionId()).isEqualTo(new SessionId("bar")); + assertThat(decoded.getParameters()).isEmpty(); } @Test @@ -201,7 +181,7 @@ public void canExtractSessionIdFromRequestBody() { codec.defineCommand("foo", POST, "/foo/bar/baz"); Command decoded = codec.decode(request); - assertThat(decoded.getSessionId(), is(new SessionId("sessionX"))); + assertThat(decoded.getSessionId()).isEqualTo(new SessionId("sessionX")); } @Test @@ -210,9 +190,9 @@ public void extractsAllParametersFromUrl() { codec.defineCommand("pick", GET, "/fruit/:fruit/size/:size"); Command decoded = codec.decode(request); - assertThat(decoded.getParameters(), is((Map) ImmutableMap.of( + assertThat(decoded.getParameters()).isEqualTo((Map) ImmutableMap.of( "fruit", "apple", - "size", "large"))); + "size", "large")); } @Test @@ -229,9 +209,9 @@ public void extractsAllParameters() { codec.defineCommand("pick", POST, "/fruit/:fruit/size/:size"); Command decoded = codec.decode(request); - assertThat(decoded.getSessionId(), is(new SessionId("sessionX"))); - assertThat(decoded.getParameters(), is((Map) ImmutableMap.of( - "fruit", "apple", "size", "large", "color", "red"))); + assertThat(decoded.getSessionId()).isEqualTo(new SessionId("sessionX")); + assertThat(decoded.getParameters()).isEqualTo((Map) ImmutableMap.of( + "fruit", "apple", "size", "large", "color", "red")); } @Test @@ -248,9 +228,9 @@ public void ignoresNullSessionIdInSessionBody() { codec.defineCommand("pick", POST, "/fruit/:fruit/size/:size"); Command decoded = codec.decode(request); - assertThat(decoded.getSessionId(), is(nullValue())); - assertThat(decoded.getParameters(), is((Map) ImmutableMap.of( - "fruit", "apple", "size", "large", "color", "red"))); + assertThat(decoded.getSessionId()).isNull(); + assertThat(decoded.getParameters()).isEqualTo((Map) ImmutableMap.of( + "fruit", "apple", "size", "large", "color", "red")); } @Test @@ -264,7 +244,7 @@ public void decodeRequestWithUtf16Encoding() { request.setContent(data); Command command = codec.decode(request); - assertThat((String) command.getParameters().get("char"), is("æ°´")); + assertThat((String) command.getParameters().get("char")).isEqualTo("æ°´"); } @Test @@ -278,7 +258,7 @@ public void decodingUsesUtf8IfNoEncodingSpecified() { request.setContent(data); Command command = codec.decode(request); - assertThat((String) command.getParameters().get("char"), is("æ°´")); + assertThat((String) command.getParameters().get("char")).isEqualTo("æ°´"); } @Test @@ -290,9 +270,9 @@ public void codecRoundTrip() { HttpRequest request = codec.encode(original); Command decoded = codec.decode(request); - assertThat(decoded.getName(), is(original.getName())); - assertThat(decoded.getSessionId(), is(original.getSessionId())); - assertThat(decoded.getParameters(), is((Map) original.getParameters())); + assertThat(decoded.getName()).isEqualTo(original.getName()); + assertThat(decoded.getSessionId()).isEqualTo(original.getSessionId()); + assertThat(decoded.getParameters()).isEqualTo((Map) original.getParameters()); } @Test @@ -306,7 +286,7 @@ public void treatsEmptyPathAsRoot_recognizedCommand() { request.setContent(data); Command command = codec.decode(request); - assertThat(command.getName(), is("num")); + assertThat(command.getName()).isEqualTo("num"); } @Test @@ -320,7 +300,7 @@ public void treatsNullPathAsRoot_recognizedCommand() { request.setContent(data); Command command = codec.decode(request); - assertThat(command.getName(), is("num")); + assertThat(command.getName()).isEqualTo("num"); } @Test @@ -333,12 +313,8 @@ public void treatsEmptyPathAsRoot_unrecognizedCommand() { request.setHeader(CONTENT_LENGTH, String.valueOf(data.length)); request.setContent(data); - try { - codec.decode(request); - fail(); - } catch (UnsupportedCommandException expected) { - // Do nothing. - } + assertThatExceptionOfType(UnsupportedCommandException.class) + .isThrownBy(() -> codec.decode(request)); } @Test @@ -351,12 +327,8 @@ public void treatsNullPathAsRoot_unrecognizedCommand() { request.setHeader(CONTENT_LENGTH, String.valueOf(data.length)); request.setContent(data); - try { - codec.decode(request); - fail(); - } catch (UnsupportedCommandException expected) { - // Do nothing. - } + assertThatExceptionOfType(UnsupportedCommandException.class) + .isThrownBy(() -> codec.decode(request)); } @Test @@ -375,6 +347,6 @@ public void whenDecodingAnHttpRequestDoesNotRecreateWebElements() { List args = (List) decoded.getParameters().get("args"); Map element = (Map) args.get(0); - assertEquals("67890", element.get(OSS.getEncodedElementKey())); + assertThat(element.get(OSS.getEncodedElementKey())).isEqualTo("67890"); } } diff --git a/java/client/test/org/openqa/selenium/remote/http/JsonHttpResponseCodecTest.java b/java/client/test/org/openqa/selenium/remote/http/JsonHttpResponseCodecTest.java index a49277297652a..8e7c71df94a7a 100644 --- a/java/client/test/org/openqa/selenium/remote/http/JsonHttpResponseCodecTest.java +++ b/java/client/test/org/openqa/selenium/remote/http/JsonHttpResponseCodecTest.java @@ -26,17 +26,11 @@ import static java.net.HttpURLConnection.HTTP_OK; import static java.nio.charset.StandardCharsets.UTF_16; import static java.nio.charset.StandardCharsets.UTF_8; -import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import com.google.common.collect.ImmutableMap; import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; import org.openqa.selenium.ScriptTimeoutException; import org.openqa.selenium.WebDriverException; import org.openqa.selenium.json.Json; @@ -45,7 +39,6 @@ import org.openqa.selenium.remote.RemoteWebElement; import org.openqa.selenium.remote.Response; -@RunWith(JUnit4.class) public class JsonHttpResponseCodecTest { private final JsonHttpResponseCodec codec = new JsonHttpResponseCodec(); @@ -57,15 +50,15 @@ public void convertsResponses_success() { response.setValue(ImmutableMap.of("color", "red")); HttpResponse converted = codec.encode(HttpResponse::new, response); - assertThat(converted.getStatus(), is(HTTP_OK)); - assertThat(converted.getHeader(CONTENT_TYPE), is(JSON_UTF_8.toString())); + assertThat(converted.getStatus()).isEqualTo(HTTP_OK); + assertThat(converted.getHeader(CONTENT_TYPE)).isEqualTo(JSON_UTF_8.toString()); Response rebuilt = new Json().toType(new String(converted.getContent(), UTF_8), Response.class); - assertEquals(response.getStatus(), rebuilt.getStatus()); - assertEquals(new ErrorCodes().toState(response.getStatus()), rebuilt.getState()); - assertEquals(response.getSessionId(), rebuilt.getSessionId()); - assertEquals(response.getValue(), rebuilt.getValue()); + assertThat(rebuilt.getStatus()).isEqualTo(response.getStatus()); + assertThat(rebuilt.getState()).isEqualTo(new ErrorCodes().toState(response.getStatus())); + assertThat(rebuilt.getSessionId()).isEqualTo(response.getSessionId()); + assertThat(rebuilt.getValue()).isEqualTo(response.getValue()); } @Test @@ -75,15 +68,15 @@ public void convertsResponses_failure() { response.setValue(ImmutableMap.of("color", "red")); HttpResponse converted = codec.encode(HttpResponse::new, response); - assertThat(converted.getStatus(), is(HTTP_INTERNAL_ERROR)); - assertThat(converted.getHeader(CONTENT_TYPE), is(JSON_UTF_8.toString())); + assertThat(converted.getStatus()).isEqualTo(HTTP_INTERNAL_ERROR); + assertThat(converted.getHeader(CONTENT_TYPE)).isEqualTo(JSON_UTF_8.toString()); Response rebuilt = new Json().toType(new String(converted.getContent(), UTF_8), Response.class); - assertEquals(response.getStatus(), rebuilt.getStatus()); - assertEquals(new ErrorCodes().toState(response.getStatus()), rebuilt.getState()); - assertEquals(response.getSessionId(), rebuilt.getSessionId()); - assertEquals(response.getValue(), rebuilt.getValue()); + assertThat(rebuilt.getStatus()).isEqualTo(response.getStatus()); + assertThat(rebuilt.getState()).isEqualTo(new ErrorCodes().toState(response.getStatus())); + assertThat(rebuilt.getSessionId()).isEqualTo(response.getSessionId()); + assertThat(rebuilt.getValue()).isEqualTo(response.getValue()); } @Test @@ -95,9 +88,9 @@ public void roundTrip() { HttpResponse httpResponse = codec.encode(HttpResponse::new, response); Response decoded = codec.decode(httpResponse); - assertEquals(response.getStatus(), decoded.getStatus()); - assertEquals(response.getSessionId(), decoded.getSessionId()); - assertEquals(response.getValue(), decoded.getValue()); + assertThat(decoded.getStatus()).isEqualTo(response.getStatus()); + assertThat(decoded.getSessionId()).isEqualTo(response.getSessionId()); + assertThat(decoded.getValue()).isEqualTo(response.getValue()); } @Test @@ -107,8 +100,8 @@ public void decodeNonJsonResponse_200() { response.setContent("{\"foobar\"}".getBytes(UTF_8)); Response decoded = codec.decode(response); - assertEquals(0, decoded.getStatus().longValue()); - assertEquals("{\"foobar\"}", decoded.getValue()); + assertThat(decoded.getStatus().longValue()).isEqualTo(0); + assertThat(decoded.getValue()).isEqualTo("{\"foobar\"}"); } @Test @@ -117,8 +110,8 @@ public void decodeNonJsonResponse_204() { response.setStatus(HTTP_NO_CONTENT); Response decoded = codec.decode(response); - assertNull(decoded.getStatus()); - assertNull(decoded.getValue()); + assertThat(decoded.getStatus()).isNull(); + assertThat(decoded.getValue()).isNull(); } @Test @@ -128,8 +121,8 @@ public void decodeNonJsonResponse_4xx() { response.setContent("{\"foobar\"}".getBytes(UTF_8)); Response decoded = codec.decode(response); - assertEquals(ErrorCodes.UNKNOWN_COMMAND, decoded.getStatus().intValue()); - assertEquals("{\"foobar\"}", decoded.getValue()); + assertThat(decoded.getStatus().intValue()).isEqualTo(ErrorCodes.UNKNOWN_COMMAND); + assertThat(decoded.getValue()).isEqualTo("{\"foobar\"}"); } @Test @@ -139,8 +132,8 @@ public void decodeNonJsonResponse_5xx() { response.setContent("{\"foobar\"}".getBytes(UTF_8)); Response decoded = codec.decode(response); - assertEquals(ErrorCodes.UNHANDLED_ERROR, decoded.getStatus().intValue()); - assertEquals("{\"foobar\"}", decoded.getValue()); + assertThat(decoded.getStatus().intValue()).isEqualTo(ErrorCodes.UNHANDLED_ERROR); + assertThat(decoded.getValue()).isEqualTo("{\"foobar\"}"); } @Test @@ -154,9 +147,9 @@ public void decodeJsonResponseMissingContentType() { httpResponse.setContent(new Json().toJson(response).getBytes(UTF_8)); Response decoded = codec.decode(httpResponse); - assertEquals(response.getStatus(), decoded.getStatus()); - assertEquals(response.getSessionId(), decoded.getSessionId()); - assertEquals(response.getValue(), decoded.getValue()); + assertThat(decoded.getStatus()).isEqualTo(response.getStatus()); + assertThat(decoded.getSessionId()).isEqualTo(response.getSessionId()); + assertThat(decoded.getValue()).isEqualTo(response.getValue()); } @Test @@ -167,7 +160,7 @@ public void decodeUtf16EncodedResponse() { httpResponse.setContent("{\"status\":0,\"value\":\"æ°´\"}".getBytes(UTF_16)); Response response = codec.decode(httpResponse); - assertEquals("æ°´", response.getValue()); + assertThat(response.getValue()).isEqualTo("æ°´"); } @Test @@ -177,8 +170,8 @@ public void decodeJsonResponseWithTrailingNullBytes() { response.setContent("{\"status\":0,\"value\":\"foo\"}\0\0".getBytes(UTF_8)); Response decoded = codec.decode(response); - assertEquals(ErrorCodes.SUCCESS, decoded.getStatus().intValue()); - assertEquals("foo", decoded.getValue()); + assertThat(decoded.getStatus().intValue()).isEqualTo(ErrorCodes.SUCCESS); + assertThat(decoded.getValue()).isEqualTo("foo"); } @Test @@ -190,7 +183,7 @@ public void shouldConvertElementReferenceToRemoteWebElement() { "value", ImmutableMap.of(Dialect.OSS.getEncodedElementKey(), "345678"))).getBytes(UTF_8)); Response decoded = codec.decode(response); - assertEquals("345678", ((RemoteWebElement) decoded.getValue()).getId()); + assertThat(((RemoteWebElement) decoded.getValue()).getId()).isEqualTo("345678"); } @Test @@ -205,10 +198,10 @@ public void shouldAttemptToConvertAnExceptionIntoAnActualExceptionInstance() { httpResponse.setContent(new Json().toJson(response).getBytes(UTF_8)); Response decoded = codec.decode(httpResponse); - assertEquals(ErrorCodes.ASYNC_SCRIPT_TIMEOUT, decoded.getStatus().intValue()); + assertThat(decoded.getStatus().intValue()).isEqualTo(ErrorCodes.ASYNC_SCRIPT_TIMEOUT); WebDriverException seenException = (WebDriverException) decoded.getValue(); - assertEquals(exception.getClass(), seenException.getClass()); - assertTrue(seenException.getMessage().startsWith(exception.getMessage())); + assertThat(seenException.getClass()).isEqualTo(exception.getClass()); + assertThat(seenException.getMessage().startsWith(exception.getMessage())).isTrue(); } } diff --git a/java/client/test/org/openqa/selenium/remote/http/W3CHttpResponseCodecTest.java b/java/client/test/org/openqa/selenium/remote/http/W3CHttpResponseCodecTest.java index 51f459e15957b..d87099dd62ecd 100644 --- a/java/client/test/org/openqa/selenium/remote/http/W3CHttpResponseCodecTest.java +++ b/java/client/test/org/openqa/selenium/remote/http/W3CHttpResponseCodecTest.java @@ -20,8 +20,7 @@ import static java.net.HttpURLConnection.HTTP_INTERNAL_ERROR; import static java.net.HttpURLConnection.HTTP_OK; import static java.nio.charset.StandardCharsets.UTF_8; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.openqa.selenium.remote.ErrorCodes.METHOD_NOT_ALLOWED; import com.google.common.collect.ImmutableMap; @@ -49,9 +48,9 @@ public void noErrorNoCry() { Response decoded = new W3CHttpResponseCodec().decode(response); - assertEquals(ErrorCodes.SUCCESS, decoded.getStatus().intValue()); - assertEquals("success", decoded.getState()); - assertEquals("cheese", decoded.getValue()); + assertThat(decoded.getStatus().intValue()).isEqualTo(ErrorCodes.SUCCESS); + assertThat(decoded.getState()).isEqualTo("success"); + assertThat(decoded.getValue()).isEqualTo("cheese"); } @Test @@ -65,11 +64,11 @@ public void decodingAnErrorWithoutAStacktraceIsDecodedProperlyForNonCompliantImp Response decoded = new W3CHttpResponseCodec().decode(response); - assertEquals("unsupported operation", decoded.getState()); - assertEquals(METHOD_NOT_ALLOWED, decoded.getStatus().intValue()); + assertThat(decoded.getState()).isEqualTo("unsupported operation"); + assertThat(decoded.getStatus().intValue()).isEqualTo(METHOD_NOT_ALLOWED); - assertTrue(decoded.getValue() instanceof UnsupportedCommandException); - assertTrue(((WebDriverException) decoded.getValue()).getMessage().contains("I like peas")); + assertThat(decoded.getValue()).isInstanceOf(UnsupportedCommandException.class); + assertThat(((WebDriverException) decoded.getValue()).getMessage()).contains("I like peas"); } @Test @@ -85,11 +84,11 @@ public void decodingAnErrorWithoutAStacktraceIsDecodedProperlyForConformingImple Response decoded = new W3CHttpResponseCodec().decode(response); - assertEquals("unsupported operation", decoded.getState()); - assertEquals(METHOD_NOT_ALLOWED, decoded.getStatus().intValue()); + assertThat(decoded.getState()).isEqualTo("unsupported operation"); + assertThat(decoded.getStatus().intValue()).isEqualTo(METHOD_NOT_ALLOWED); - assertTrue(decoded.getValue() instanceof UnsupportedCommandException); - assertTrue(((WebDriverException) decoded.getValue()).getMessage().contains("I like peas")); + assertThat(decoded.getValue()).isInstanceOf(UnsupportedCommandException.class); + assertThat(((WebDriverException) decoded.getValue()).getMessage()).contains("I like peas"); } @Test @@ -105,7 +104,7 @@ public void shouldPopulateTheAlertTextIfThrowingAnUnhandledAlertException() { Response decoded = new W3CHttpResponseCodec().decode(response); UnhandledAlertException ex = (UnhandledAlertException) decoded.getValue(); - assertEquals("cheese", ex.getAlertText()); + assertThat(ex.getAlertText()).isEqualTo("cheese"); } private HttpResponse createValidResponse(int statusCode, Map data) { diff --git a/java/client/test/org/openqa/selenium/remote/internal/CircularOutputStreamTest.java b/java/client/test/org/openqa/selenium/remote/internal/CircularOutputStreamTest.java index 0b221d8192002..27411738e4cc7 100644 --- a/java/client/test/org/openqa/selenium/remote/internal/CircularOutputStreamTest.java +++ b/java/client/test/org/openqa/selenium/remote/internal/CircularOutputStreamTest.java @@ -17,19 +17,16 @@ package org.openqa.selenium.remote.internal; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import java.io.IOException; import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; import org.openqa.selenium.io.CircularOutputStream; import java.io.ByteArrayOutputStream; import java.io.PrintStream; import java.io.PrintWriter; -@RunWith(JUnit4.class) public class CircularOutputStreamTest { @Test public void testShouldReturnTheEntireWrittenContentIfSmallerThanTheBufferSize() throws Exception { @@ -41,7 +38,7 @@ public void testShouldReturnTheEntireWrittenContentIfSmallerThanTheBufferSize() String seen = os.toString(); - assertEquals(expected, seen); + assertThat(seen).isEqualTo(expected); } } @@ -56,7 +53,7 @@ public void testShouldReturnJustTheWrittenOutputIfBufferIsTooLarge() throws Exce String seen = os.toString(); - assertEquals(expected, seen); + assertThat(seen).isEqualTo(expected); } } @@ -70,7 +67,7 @@ public void testShouldTruncateOutputToMatchTheSizeOfTheBuffer() throws Exception String seen = os.toString(); - assertEquals(expected, seen); + assertThat(seen).isEqualTo(expected); } } @@ -84,7 +81,7 @@ public void testShouldReturnContentInTheCorrectOrder() throws Exception { String seen = os.toString(); - assertEquals(expected, seen); + assertThat(seen).isEqualTo(expected); } } @@ -106,7 +103,7 @@ public void testLongerMultiLineOutputPreservesJustTheEnd() { String seen = os.toString(); cops.close(); - assertEquals(expected, seen); + assertThat(seen).isEqualTo(expected); } @Test @@ -116,15 +113,15 @@ public void testCircularness() { pw.write("12345"); pw.flush(); - assertEquals("12345", os.toString()); + assertThat(os.toString()).isEqualTo("12345"); pw.write("6"); pw.flush(); - assertEquals("23456", os.toString()); + assertThat(os.toString()).isEqualTo("23456"); pw.write("789"); pw.flush(); - assertEquals("56789", os.toString()); + assertThat(os.toString()).isEqualTo("56789"); } } @@ -149,8 +146,8 @@ public void testConcurrentWrites() throws InterruptedException { b++; } } - assertEquals(bytesToWrite, a); - assertEquals(bytesToWrite, b); + assertThat(a).isEqualTo(bytesToWrite); + assertThat(b).isEqualTo(bytesToWrite); } private static class WriteChar implements Runnable { diff --git a/java/client/test/org/openqa/selenium/remote/internal/HttpClientTestBase.java b/java/client/test/org/openqa/selenium/remote/internal/HttpClientTestBase.java index b9b260ab02cd4..4c872d334e061 100644 --- a/java/client/test/org/openqa/selenium/remote/internal/HttpClientTestBase.java +++ b/java/client/test/org/openqa/selenium/remote/internal/HttpClientTestBase.java @@ -17,9 +17,7 @@ package org.openqa.selenium.remote.internal; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.openqa.selenium.json.Json.MAP_TYPE; import static org.openqa.selenium.remote.http.HttpMethod.GET; @@ -64,7 +62,7 @@ public void responseShouldCaptureASingleHeader() throws Exception { HttpResponse response = getResponseWithHeaders(headers); String value = response.getHeader("Cake"); - assertEquals("Delicious", value); + assertThat(value).isEqualTo("Delicious"); } /** @@ -83,19 +81,19 @@ public void responseShouldKeepMultipleHeadersSeparate() throws Exception { ImmutableList values = ImmutableList.copyOf(response.getHeaders("Cheese")); - assertTrue(values.toString(), values.contains("Cheddar")); - assertTrue(values.toString(), values.contains("Brie, Gouda")); + assertThat(values).contains("Cheddar"); + assertThat(values).contains("Brie, Gouda"); } @Test public void shouldAddUrlParameters() { HttpRequest request = new HttpRequest(GET, "/query"); String value = request.getQueryParameter("cheese"); - assertNull(value); + assertThat(value).isNull(); request.addQueryParameter("cheese", "brie"); value = request.getQueryParameter("cheese"); - assertEquals("brie", value); + assertThat(value).isEqualTo("brie"); } @Test @@ -106,7 +104,7 @@ public void shouldSendSimpleQueryParameters() throws Exception { HttpResponse response = getQueryParameterResponse(request); Map values = new Json().toType(response.getContentString(), MAP_TYPE); - assertEquals(ImmutableList.of("cheddar"), values.get("cheese")); + assertThat(values).containsEntry("cheese", ImmutableList.of("cheddar")); } @Test @@ -117,7 +115,7 @@ public void shouldEncodeParameterNamesAndValues() throws Exception { HttpResponse response = getQueryParameterResponse(request); Map values = new Json().toType(response.getContentString(), MAP_TYPE); - assertEquals(ImmutableList.of("tasty cheese"), values.get("cheese type")); + assertThat(values).containsEntry("cheese type", ImmutableList.of("tasty cheese")); } @Test @@ -130,8 +128,8 @@ public void canAddMoreThanOneQueryParameter() throws Exception { HttpResponse response = getQueryParameterResponse(request); Map values = new Json().toType(response.getContentString(), MAP_TYPE); - assertEquals(ImmutableList.of("cheddar", "gouda"), values.get("cheese")); - assertEquals(ImmutableList.of("peas"), values.get("vegetable")); + assertThat(values).containsEntry("cheese", ImmutableList.of("cheddar", "gouda")); + assertThat(values).containsEntry("vegetable", ImmutableList.of("peas")); } @Test @@ -164,7 +162,7 @@ protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IO HttpResponse response = client.execute(request); - assertEquals("Hello, World!", response.getContentString()); + assertThat(response.getContentString()).isEqualTo("Hello, World!"); } finally { server.stop(); } @@ -189,13 +187,10 @@ protected void doGet(HttpServletRequest req, HttpServletResponse resp) Platform platform = Platform.getCurrent(); Platform family = platform.family() == null ? platform : platform.family(); - assertEquals( - response.getContentString(), - String.format( - "selenium/%s (java %s)", - label, - family.toString().toLowerCase()), - response.getContentString()); + assertThat(response.getContentString()).isEqualTo(String.format( + "selenium/%s (java %s)", + label, + family.toString().toLowerCase())); } private HttpResponse getResponseWithHeaders(final Multimap headers) diff --git a/java/client/test/org/openqa/selenium/remote/internal/WebElementToJsonConverterTest.java b/java/client/test/org/openqa/selenium/remote/internal/WebElementToJsonConverterTest.java index 011aa5f627635..093ce37e1f853 100644 --- a/java/client/test/org/openqa/selenium/remote/internal/WebElementToJsonConverterTest.java +++ b/java/client/test/org/openqa/selenium/remote/internal/WebElementToJsonConverterTest.java @@ -18,19 +18,13 @@ package org.openqa.selenium.remote.internal; import static java.util.Arrays.asList; -import static org.hamcrest.Matchers.instanceOf; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; import org.openqa.selenium.WebElement; import org.openqa.selenium.WrappedWebElement; import org.openqa.selenium.remote.Dialect; @@ -41,18 +35,17 @@ import java.util.List; import java.util.Map; -@RunWith(JUnit4.class) public class WebElementToJsonConverterTest { private static final WebElementToJsonConverter CONVERTER = new WebElementToJsonConverter(); @Test public void returnsPrimitivesAsIs() { - assertNull(CONVERTER.apply(null)); - assertEquals("abc", CONVERTER.apply("abc")); - assertEquals(Boolean.TRUE, CONVERTER.apply(Boolean.TRUE)); - assertEquals(Integer.valueOf(123), CONVERTER.apply(123)); - assertEquals(Math.PI, CONVERTER.apply(Math.PI)); + assertThat(CONVERTER.apply(null)).isNull(); + assertThat(CONVERTER.apply("abc")).isEqualTo("abc"); + assertThat(CONVERTER.apply(Boolean.TRUE)).isEqualTo(Boolean.TRUE); + assertThat(CONVERTER.apply(123)).isEqualTo(123); + assertThat(CONVERTER.apply(Math.PI)).isEqualTo(Math.PI); } @Test @@ -90,7 +83,7 @@ public void unwrapsWrappedElements_multipleLevelsOfWrapping() { @Test public void convertsSimpleCollections() { Object converted = CONVERTER.apply(asList(null, "abc", true, 123, Math.PI)); - assertThat(converted, instanceOf(Collection.class)); + assertThat(converted).isInstanceOf(Collection.class); List list = new ArrayList<>((Collection) converted); assertContentsInOrder(list, null, "abc", true, 123, Math.PI); @@ -102,13 +95,13 @@ public void convertsNestedCollections_simpleValues() { List outerList = asList("apples", "oranges", innerList); Object converted = CONVERTER.apply(outerList); - assertThat(converted, instanceOf(Collection.class)); + assertThat(converted).isInstanceOf(Collection.class); List list = ImmutableList.copyOf((Collection) converted); - assertEquals(3, list.size()); - assertEquals("apples", list.get(0)); - assertEquals("oranges", list.get(1)); - assertThat(list.get(2), instanceOf(Collection.class)); + assertThat(list).hasSize(3); + assertThat(list.get(0)).isEqualTo("apples"); + assertThat(list.get(1)).isEqualTo("oranges"); + assertThat(list.get(2)).isInstanceOf(Collection.class); list = ImmutableList.copyOf((Collection) list.get(2)); assertContentsInOrder(list, 123, "abc"); @@ -116,23 +109,15 @@ public void convertsNestedCollections_simpleValues() { @Test public void requiresMapsToHaveStringKeys() { - try { - CONVERTER.apply(ImmutableMap.of(new Object(), "bunny")); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThatExceptionOfType(IllegalArgumentException.class) + .isThrownBy(() -> CONVERTER.apply(ImmutableMap.of(new Object(), "bunny"))); } @Test public void requiresNestedMapsToHaveStringKeys() { - try { - CONVERTER.apply(ImmutableMap.of( - "one", ImmutableMap.of( - "two", ImmutableMap.of( - Integer.valueOf(3), "not good")))); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThatExceptionOfType(IllegalArgumentException.class) + .isThrownBy(() -> CONVERTER.apply( + ImmutableMap.of("one", ImmutableMap.of("two", ImmutableMap.of(3, "not good"))))); } @Test @@ -141,14 +126,14 @@ public void convertsASimpleMap() { "one", 1, "fruit", "apples", "honest", true)); - assertThat(converted, instanceOf(Map.class)); + assertThat(converted).isInstanceOf(Map.class); @SuppressWarnings("unchecked") Map map = (Map) converted; - assertEquals(3, map.size()); - assertEquals(1, map.get("one")); - assertEquals("apples", map.get("fruit")); - assertEquals(true, map.get("honest")); + assertThat(map).hasSize(3); + assertThat(map.get("one")).isEqualTo(1); + assertThat(map.get("fruit")).isEqualTo("apples"); + assertThat(map.get("honest")).isEqualTo(true); } @SuppressWarnings("unchecked") @@ -159,18 +144,18 @@ public void convertsANestedMap() { "fruit", "apples", "honest", true, "nested", ImmutableMap.of("bugs", "bunny"))); - assertThat(converted, instanceOf(Map.class)); + assertThat(converted).isInstanceOf(Map.class); Map map = (Map) converted; - assertEquals(4, map.size()); - assertEquals(1, map.get("one")); - assertEquals("apples", map.get("fruit")); - assertEquals(true, map.get("honest")); - assertThat(map.get("nested"), instanceOf(Map.class)); + assertThat(map).hasSize(4); + assertThat(map.get("one")).isEqualTo(1); + assertThat(map.get("fruit")).isEqualTo("apples"); + assertThat(map.get("honest")).isEqualTo(true); + assertThat(map.get("nested")).isInstanceOf(Map.class); map = (Map) map.get("nested"); - assertEquals(1, map.size()); - assertEquals("bunny", map.get("bugs")); + assertThat(map.size()).isEqualTo(1); + assertThat(map.get("bugs")).isEqualTo("bunny"); } @SuppressWarnings("unchecked") @@ -183,10 +168,10 @@ public void convertsAListWithAWebElement() { element2.setId("anotherId"); Object value = CONVERTER.apply(asList(element, element2)); - assertThat(value, instanceOf(Collection.class)); + assertThat(value).isInstanceOf(Collection.class); List list = new ArrayList<>((Collection) value); - assertEquals(2, list.size()); + assertThat(list).hasSize(2); assertIsWebElementObject(list.get(0), "abc123"); assertIsWebElementObject(list.get(1), "anotherId"); } @@ -198,10 +183,10 @@ public void convertsAMapWithAWebElement() { element.setId("abc123"); Object value = CONVERTER.apply(ImmutableMap.of("one", element)); - assertThat(value, instanceOf(Map.class)); + assertThat(value).isInstanceOf(Map.class); Map map = (Map) value; - assertEquals(1, map.size()); + assertThat(map.size()).isEqualTo(1); assertIsWebElementObject(map.get("one"), "abc123"); } @@ -211,7 +196,7 @@ public void convertsAnArray() { "abc123", true, 123, Math.PI }); - assertThat(value, instanceOf(Collection.class)); + assertThat(value).isInstanceOf(Collection.class); assertContentsInOrder(new ArrayList<>((Collection) value), "abc123", true, 123, Math.PI); } @@ -230,11 +215,8 @@ public void convertsAnArrayWithAWebElement() { @Test public void rejectsUnrecognizedTypes() { - try { - CONVERTER.apply(new Object()); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThatExceptionOfType(IllegalArgumentException.class) + .isThrownBy(() -> CONVERTER.apply(new Object())); } private static WrappedWebElement wrapElement(WebElement element) { @@ -242,19 +224,19 @@ private static WrappedWebElement wrapElement(WebElement element) { } private static void assertIsWebElementObject(Object value, String expectedKey) { - assertThat(value, instanceOf(Map.class)); + assertThat(value).isInstanceOf(Map.class); Map map = (Map) value; - assertEquals(2, map.size()); - assertTrue(map.containsKey(Dialect.OSS.getEncodedElementKey())); - assertEquals(expectedKey, map.get(Dialect.OSS.getEncodedElementKey())); - assertTrue(map.containsKey(Dialect.W3C.getEncodedElementKey())); - assertEquals(expectedKey, map.get(Dialect.W3C.getEncodedElementKey())); + assertThat(map).hasSize(2); + assertThat(map.containsKey(Dialect.OSS.getEncodedElementKey())).isTrue(); + assertThat(map.get(Dialect.OSS.getEncodedElementKey())).isEqualTo(expectedKey); + assertThat(map.containsKey(Dialect.W3C.getEncodedElementKey())).isTrue(); + assertThat(map.get(Dialect.W3C.getEncodedElementKey())).isEqualTo(expectedKey); } private static void assertContentsInOrder(List list, Object... expectedContents) { List expected = asList(expectedContents); - assertEquals(expected, list); + assertThat(list).isEqualTo(expected); } } diff --git a/java/client/test/org/openqa/selenium/safari/AlertsTest.java b/java/client/test/org/openqa/selenium/safari/AlertsTest.java deleted file mode 100644 index ee2fbbb85da0d..0000000000000 --- a/java/client/test/org/openqa/selenium/safari/AlertsTest.java +++ /dev/null @@ -1,300 +0,0 @@ -// Licensed to the Software Freedom Conservancy (SFC) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The SFC licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package org.openqa.selenium.safari; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; - -import com.google.common.base.Joiner; - -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.Test; -import org.openqa.selenium.By; -import org.openqa.selenium.JavascriptExecutor; -import org.openqa.selenium.NoAlertPresentException; -import org.openqa.selenium.UnhandledAlertException; -import org.openqa.selenium.WebElement; -import org.openqa.selenium.testing.JUnit4TestBase; -import org.openqa.selenium.testing.NeedsLocalEnvironment; - -import java.util.concurrent.TimeUnit; - -@NeedsLocalEnvironment(reason = "Requires local browser launching environment") -public class AlertsTest extends JUnit4TestBase { - - @AfterClass - public static void quitDriver() { - JUnit4TestBase.removeDriver(); - } - - @Before - public void setUp() { - driver.get(pages.alertsPage); - } - - @Test - public void testShouldBeAbleToOverrideTheWindowAlertMethod() { - ((JavascriptExecutor) driver).executeScript( - "window.alert = function(msg) { document.getElementById('text').innerHTML = msg; }"); - driver.findElement(By.id("alert")).click(); - } - - @Test - public void testHandlesWhenNoAlertsArePresent() { - try { - driver.switchTo().alert(); - } catch (NoAlertPresentException expected) { - } - } - - @Test - public void testCatchesAlertsOpenedWithinAnIFrame() { - driver.switchTo().frame("iframeWithAlert"); - - try { - driver.findElement(By.id("alertInFrame")).click(); - } catch (UnhandledAlertException expected) { - } - - // If we can perform any action, we're good to go - assertEquals("Testing Alerts", driver.getTitle()); - } - - @Test - public void throwsIfScriptTriggersAlert() { - driver.get(pages.simpleTestPage); - driver.manage().timeouts().setScriptTimeout(5000, TimeUnit.MILLISECONDS); - try { - ((JavascriptExecutor)driver).executeAsyncScript("setTimeout(arguments[0], 200) ; setTimeout(function() { window.alert('Look! An alert!'); }, 50);"); - fail("Expected UnhandledAlertException"); - } catch (UnhandledAlertException expected) { - // Expected exception - } - // Shouldn't throw - driver.getTitle(); - } - - @Test - public void throwsIfAlertHappensDuringScript() { - driver.get(pages.slowLoadingAlertPage); - driver.manage().timeouts().setScriptTimeout(5000, TimeUnit.MILLISECONDS); - try { - ((JavascriptExecutor)driver).executeAsyncScript("setTimeout(arguments[0], 1000);"); - fail("Expected UnhandledAlertException"); - } catch (UnhandledAlertException expected) { - //Expected exception - } - // Shouldn't throw - driver.getTitle(); - } - - @Test - public void throwsIfScriptTriggersAlertWhichTimesOut() { - driver.get(pages.simpleTestPage); - driver.manage().timeouts().setScriptTimeout(5000, TimeUnit.MILLISECONDS); - try { - ((JavascriptExecutor)driver).executeAsyncScript("setTimeout(function() { window.alert('Look! An alert!'); }, 50);"); - fail("Expected UnhandledAlertException"); - } catch (UnhandledAlertException expected) { - // Expected exception - } - // Shouldn't throw - driver.getTitle(); - } - - @Test - public void throwsIfAlertHappensDuringScriptWhichTimesOut() { - driver.get(pages.slowLoadingAlertPage); - driver.manage().timeouts().setScriptTimeout(5000, TimeUnit.MILLISECONDS); - try { - ((JavascriptExecutor)driver).executeAsyncScript(""); - fail("Expected UnhandledAlertException"); - } catch (UnhandledAlertException expected) { - //Expected exception - } - // Shouldn't throw - driver.getTitle(); - } - - @Test - public void testIncludesAlertInUnhandledAlertException() { - try { - driver.findElement(By.id("alert")).click(); - fail("Expected UnhandledAlertException"); - } catch (UnhandledAlertException e) { - assertAlertText("cheese", e); - } - } - - @Test - public void shouldCatchAlertsOpenedBetweenCommandsAndReportThemOnTheNextCommand() - throws InterruptedException { - driver.get(pages.alertsPage); - ((JavascriptExecutor)driver).executeScript( - "setTimeout(function() { alert('hi'); }, 250);"); - Thread.sleep(1000); - try { - driver.getTitle(); - } catch (UnhandledAlertException expected) { - assertAlertText("hi", expected); - } - // Shouldn't throw - driver.getTitle(); - } - - @Test - public void onBeforeUnloadWithNoReturnValueShouldNotTriggerUnexpectedAlertErrors() { - driver.get(pages.alertsPage); - - JavascriptExecutor executor = (JavascriptExecutor) driver; - assertEquals(0L, - executor.executeScript("localStorage.clear(); return localStorage.length")); - - executor.executeScript( - "window.onbeforeunload = function() {\n" + - " localStorage.setItem('foo', 'bar');\n" + - "};"); - - driver.navigate().refresh(); - assertEquals("onbeforeunload did not run!", - "bar", executor.executeScript("return localStorage.getItem('foo');")); - } - - @Test - public void - onBeforeUnloadWithNoReturnValueShouldNotTriggerUnexpectedAlertErrors_firedBetweenCommands() - throws InterruptedException { - driver.get(pages.alertsPage); - - JavascriptExecutor executor = (JavascriptExecutor) driver; - assertEquals(0L, - executor.executeScript("localStorage.clear(); return localStorage.length")); - - executor.executeScript( - Joiner.on("\n").join( - "window.onbeforeunload = function() {", - " localStorage.setItem('foo', 'bar');", - "};", - "var newUrl = arguments[0];", - "window.setTimeout(function() {", - " window.location.href = newUrl;", - "}, 500);"), - pages.iframePage); - - // Yes, we need to use a dirty sleep here. We want to ensure the page - // reloads and triggers onbeforeunload without any WebDriver commands. - Thread.sleep(1500); - - assertEquals(pages.iframePage, driver.getCurrentUrl()); - assertEquals("onbeforeunload did not run!", - "bar", executor.executeScript("return localStorage.getItem('foo');")); - } - - @Test - public void onBeforeUnloadWithNullReturnDoesNotTriggerAlertError() { - driver.get(pages.alertsPage); - - JavascriptExecutor executor = (JavascriptExecutor) driver; - assertEquals(0L, - executor.executeScript("localStorage.clear(); return localStorage.length")); - - executor.executeScript( - "window.onbeforeunload = function() {\n" + - " localStorage.setItem('foo', 'bar');\n" + - " return null;\n" + - "};"); - - driver.navigate().refresh(); - assertEquals("onbeforeunload did not run!", - "bar", executor.executeScript("return localStorage.getItem('foo');")); - } - - @Test - public void onBeforeUnloadFromPageLoadShouldTriggerUnexpectedAlertErrors() { - driver.get(pages.alertsPage); - - setSimpleOnBeforeUnload("one two three"); - try { - driver.get(pages.alertsPage); - fail("Expected UnhandledAlertException"); - } catch (UnhandledAlertException e) { - assertAlertText("one two three", e); - } - } - - @Test - public void onBeforeUnloadFromPageRefreshShouldTriggerUnexpectedAlertErrors() { - driver.get(pages.alertsPage); - - setSimpleOnBeforeUnload("one two three"); - try { - driver.navigate().refresh(); - fail("Expected UnhandledAlertException"); - } catch (UnhandledAlertException e) { - assertAlertText("one two three", e); - } - } - - @Test - public void - onBeforeUnloadWithReturnValuesShouldTriggerUnexpectedAlertErrors_uiAction() { - driver.get(pages.alertsPage); - - JavascriptExecutor executor = (JavascriptExecutor) driver; - WebElement body = (WebElement) executor.executeScript( - "var newPage = arguments[0];" + - "window.onbeforeunload = function() { return 'one two three'; };" + - "document.body.onclick = function() { window.location.href = newPage; };" + - "return document.body;", - pages.simpleTestPage); - - body.click(); - try { - driver.getTitle(); - fail("Expected UnhandledAlertException"); - } catch (UnhandledAlertException e) { - assertAlertText("one two three", e); - } - } - - @Test - public void - onBeforeUnloadWithReturnValuesShouldTriggerUnexpectedAlertErrors_asyncScript() { - driver.get(pages.alertsPage); - - setSimpleOnBeforeUnload("one two three"); - try { - ((JavascriptExecutor) driver).executeAsyncScript( - "window.location = arguments[0]", pages.alertsPage); - fail("Expected UnhandledAlertException"); - } catch (UnhandledAlertException e) { - assertAlertText("one two three", e); - } - } - - private static void assertAlertText(String expectedText, UnhandledAlertException e) { - assertEquals(expectedText, e.getAlertText()); - } - - private void setSimpleOnBeforeUnload(Object returnValue) { - ((JavascriptExecutor) driver).executeScript( - "var retVal = arguments[0]; window.onbeforeunload = function() { return retVal; }", - returnValue); - } -} diff --git a/java/client/test/org/openqa/selenium/safari/CleanSessionTest.java b/java/client/test/org/openqa/selenium/safari/CleanSessionTest.java index 93f48248ac782..cda706853dc6e 100644 --- a/java/client/test/org/openqa/selenium/safari/CleanSessionTest.java +++ b/java/client/test/org/openqa/selenium/safari/CleanSessionTest.java @@ -17,8 +17,7 @@ package org.openqa.selenium.safari; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.openqa.selenium.testing.Driver.SAFARI; import org.junit.After; @@ -96,7 +95,7 @@ public void executeAsyncScriptIsResilientToPagesRedefiningSetTimeout() { "window.constructor.prototype.setTimeout.call(window, function() {" + "callback(123);\n}, 0);"); - assertEquals(123L, result); + assertThat(result).isEqualTo(123L); } @Test @@ -109,23 +108,23 @@ public void doesNotLeakInternalMessagesToThePageUnderTest() { long numMessages = (Long) executor.executeScript( "return window.messages.length;"); - assertEquals(1L, numMessages); + assertThat(numMessages).isEqualTo(1L); } @Test public void doesNotCreateExtraIframeOnPageUnderTest() { driver.get(appServer.whereIs("messages.html")); - assertEquals(0, driver.findElements(By.tagName("iframe")).size()); + assertThat(driver.findElements(By.tagName("iframe"))).hasSize(0); ((JavascriptExecutor) driver).executeScript("return location.href;"); - assertEquals(0, driver.findElements(By.tagName("iframe")).size()); + assertThat(driver.findElements(By.tagName("iframe"))).hasSize(0); } private void assertHasCookie(Cookie cookie) { - assertTrue(driver2.manage().getCookies().contains(cookie)); + assertThat(driver2.manage().getCookies()).contains(cookie); } private void assertNoCookies() { - assertTrue(driver2.manage().getCookies().isEmpty()); + assertThat(driver2.manage().getCookies()).isEmpty(); } } diff --git a/java/client/test/org/openqa/selenium/safari/CrossDomainTest.java b/java/client/test/org/openqa/selenium/safari/CrossDomainTest.java index f1ae705e5b4e5..02b1180ded11d 100644 --- a/java/client/test/org/openqa/selenium/safari/CrossDomainTest.java +++ b/java/client/test/org/openqa/selenium/safari/CrossDomainTest.java @@ -17,10 +17,8 @@ package org.openqa.selenium.safari; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import org.junit.AfterClass; import org.junit.BeforeClass; @@ -65,43 +63,37 @@ public static void stopSecondServer() { @Test public void canNavigateBetweenDomains() { driver.get(pages.iframePage); - assertEquals(pages.iframePage, driver.getCurrentUrl()); + assertThat(driver.getCurrentUrl()).isEqualTo(pages.iframePage); WebElement body1 = driver.findElement(By.tagName("body")); driver.get(otherPages.iframePage); - assertEquals(otherPages.iframePage, driver.getCurrentUrl()); + assertThat(driver.getCurrentUrl()).isEqualTo(otherPages.iframePage); driver.findElement(By.tagName("body")); - try { - body1.getTagName(); - fail(); - } catch (StaleElementReferenceException expected) { - } + assertThatExceptionOfType(StaleElementReferenceException.class) + .isThrownBy(body1::getTagName); } @Test public void canSwitchToAFrameFromAnotherDomain() { setupCrossDomainFrameTest(); - assertEquals(otherPages.iframePage, getPageUrl()); + assertThat(getPageUrl()).isEqualTo(otherPages.iframePage); driver.switchTo().defaultContent(); - assertEquals(pages.iframePage, getPageUrl()); + assertThat(getPageUrl()).isEqualTo(pages.iframePage); } @Test public void cannotCrossDomainsWithExecuteScript() { setupCrossDomainFrameTest(); - try { - ((JavascriptExecutor) driver).executeScript( - "return window.top.document.body.tagName"); - fail(); - } catch (WebDriverException expected) { - } + assertThatExceptionOfType(WebDriverException.class) + .isThrownBy(() -> ((JavascriptExecutor) driver).executeScript( + "return window.top.document.body.tagName")); // Make sure we can recover from the above. - assertEquals("body", ((JavascriptExecutor) driver).executeScript( - "return window.document.body.tagName.toLowerCase();")); + assertThat(((JavascriptExecutor) driver).executeScript( + "return window.document.body.tagName.toLowerCase();")).isEqualTo("body"); } private void setupCrossDomainFrameTest() { @@ -111,9 +103,9 @@ private void setupCrossDomainFrameTest() { ((JavascriptExecutor) driver).executeScript( "arguments[0].src = arguments[1];", iframe, otherPages.iframePage); - assertTrue(isTop()); + assertThat(isTop()).isTrue(); driver.switchTo().frame(iframe); - assertFalse(isTop()); + assertThat(isTop()).isFalse(); wait.until(frameLocationToBe(otherPages.iframePage)); } diff --git a/java/client/test/org/openqa/selenium/safari/SafariDriverTest.java b/java/client/test/org/openqa/selenium/safari/SafariDriverTest.java index 2eb6728aa79ba..94fc35cd1358e 100644 --- a/java/client/test/org/openqa/selenium/safari/SafariDriverTest.java +++ b/java/client/test/org/openqa/selenium/safari/SafariDriverTest.java @@ -18,7 +18,7 @@ package org.openqa.selenium.safari; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assume.assumeTrue; import org.junit.After; @@ -61,7 +61,7 @@ public void canStartADriverUsingAService() throws IOException { service.start(); driver2 = new SafariDriver(service); driver2.get(pages.xhtmlTestPage); - assertEquals("XHTML Test Page", driver2.getTitle()); + assertThat(driver2.getTitle()).isEqualTo("XHTML Test Page"); } @Test @@ -72,7 +72,7 @@ public void canStartTechnologyPreview() { options.setUseTechnologyPreview(true); driver2 = new SafariDriver(options); driver2.get(pages.xhtmlTestPage); - assertEquals("XHTML Test Page", driver2.getTitle()); + assertThat(driver2.getTitle()).isEqualTo("XHTML Test Page"); } } diff --git a/java/client/test/org/openqa/selenium/safari/SafariDriverTests.java b/java/client/test/org/openqa/selenium/safari/SafariDriverTests.java index 06b01dcf5ba16..3a8105100384b 100644 --- a/java/client/test/org/openqa/selenium/safari/SafariDriverTests.java +++ b/java/client/test/org/openqa/selenium/safari/SafariDriverTests.java @@ -29,7 +29,6 @@ @RunWith(Suite.class) @Suite.SuiteClasses({ StandardSeleniumTests.class, - //AlertsTest.class, SafariDriverTest.class, CleanSessionTest.class, CrossDomainTest.class, diff --git a/java/client/test/org/openqa/selenium/safari/SafariOptionsTest.java b/java/client/test/org/openqa/selenium/safari/SafariOptionsTest.java index 808bcbcefe0f2..61f78f2a8d390 100644 --- a/java/client/test/org/openqa/selenium/safari/SafariOptionsTest.java +++ b/java/client/test/org/openqa/selenium/safari/SafariOptionsTest.java @@ -17,11 +17,8 @@ package org.openqa.selenium.safari; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - import com.google.common.collect.ImmutableMap; +import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; import org.openqa.selenium.ImmutableCapabilities; @@ -40,7 +37,7 @@ public void roundTrippingToCapabilitiesAndBackWorks() { // create a new set of options. This is the round trip, ladies and gentlemen. SafariOptions seen = new SafariOptions(new ImmutableCapabilities(expected.asMap())); - assertEquals(expected, seen); + assertThat(seen).isEqualTo(expected); } @Test @@ -49,20 +46,20 @@ public void canConstructFromCapabilities() { embeddedOptions.put("technologyPreview", true); SafariOptions options = new SafariOptions(); - assertFalse(options.getUseTechnologyPreview()); + assertThat(options.getUseTechnologyPreview()).isFalse(); options = new SafariOptions(new ImmutableCapabilities(SafariOptions.CAPABILITY, embeddedOptions)); - assertTrue(options.getUseTechnologyPreview()); + assertThat(options.getUseTechnologyPreview()).isTrue(); embeddedOptions.put("technologyPreview", false); options = new SafariOptions(new ImmutableCapabilities(SafariOptions.CAPABILITY, embeddedOptions)); - assertFalse(options.getUseTechnologyPreview()); + assertThat(options.getUseTechnologyPreview()).isFalse(); options = new SafariOptions(new ImmutableCapabilities(CapabilityType.BROWSER_NAME, "Safari Technology Preview")); - assertTrue(options.getUseTechnologyPreview()); + assertThat(options.getUseTechnologyPreview()).isTrue(); options = new SafariOptions(new ImmutableCapabilities(CapabilityType.BROWSER_NAME, "safari")); - assertFalse(options.getUseTechnologyPreview()); + assertThat(options.getUseTechnologyPreview()).isFalse(); } @Test @@ -71,30 +68,30 @@ public void newerStyleCapabilityWinsOverOlderStyle() { CapabilityType.BROWSER_NAME, "Safari Technology Preview", SafariOptions.CAPABILITY, ImmutableMap.of("technologyPreview", false))); - assertTrue(options.getUseTechnologyPreview()); + assertThat(options.getUseTechnologyPreview()).isTrue(); } @Test public void canSetAutomaticInspection() { SafariOptions options = new SafariOptions().setAutomaticInspection(true); - assertTrue(options.getAutomaticInspection()); + assertThat(options.getAutomaticInspection()).isTrue(); } @Test public void canSetAutomaticProfiling() { SafariOptions options = new SafariOptions().setAutomaticProfiling(true); - assertTrue(options.getAutomaticProfiling()); + assertThat(options.getAutomaticProfiling()).isTrue(); } @Test public void settingTechnologyPreviewModeAlsoChangesBrowserName() { SafariOptions options = new SafariOptions(); - assertEquals("safari", options.getBrowserName()); + assertThat(options.getBrowserName()).isEqualTo("safari"); options.setUseTechnologyPreview(true); - assertEquals("Safari Technology Preview", options.getBrowserName()); + assertThat(options.getBrowserName()).isEqualTo("Safari Technology Preview"); options.setUseTechnologyPreview(false); - assertEquals("safari", options.getBrowserName()); + assertThat(options.getBrowserName()).isEqualTo("safari"); } } diff --git a/java/client/test/org/openqa/selenium/support/BUCK b/java/client/test/org/openqa/selenium/support/BUCK index 90fa0f433b10b..158dadf1391ee 100644 --- a/java/client/test/org/openqa/selenium/support/BUCK +++ b/java/client/test/org/openqa/selenium/support/BUCK @@ -49,7 +49,7 @@ java_library(name = 'tests', '//java/client/test/org/openqa/selenium:helpers', '//java/client/test/org/openqa/selenium/testing:test-base', '//third_party/java/guava:guava', - '//third_party/java/hamcrest:hamcrest-library', + '//third_party/java/assertj:assertj', '//third_party/java/junit:junit', '//third_party/java/mockito:mockito-core', ], diff --git a/java/client/test/org/openqa/selenium/support/ColorTest.java b/java/client/test/org/openqa/selenium/support/ColorTest.java index 32783d02b3ccc..1aa9806ff79b4 100644 --- a/java/client/test/org/openqa/selenium/support/ColorTest.java +++ b/java/client/test/org/openqa/selenium/support/ColorTest.java @@ -17,7 +17,7 @@ package org.openqa.selenium.support; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; @@ -25,139 +25,139 @@ public class ColorTest { @Test public void rgbToRgb() { String rgb = "rgb(1, 2, 3)"; - assertEquals(rgb, Color.fromString(rgb).asRgb()); + assertThat(Color.fromString(rgb).asRgb()).isEqualTo(rgb); } @Test public void rgbToRgba() { String rgb = "rgb(1, 2, 3)"; - assertEquals("rgba(1, 2, 3, 1)", Color.fromString(rgb).asRgba()); + assertThat(Color.fromString(rgb).asRgba()).isEqualTo("rgba(1, 2, 3, 1)"); } @Test public void rgbPctToRgba() { String rgba = "rgb(10%, 20%, 30%)"; - assertEquals("rgba(25, 51, 76, 1)", Color.fromString(rgba).asRgba()); + assertThat(Color.fromString(rgba).asRgba()).isEqualTo("rgba(25, 51, 76, 1)"); } @Test public void rgbAllowsWhitespace() { String rgb = "rgb(\t1, 2 , 3)"; String canonicalRgb = "rgb(1, 2, 3)"; - assertEquals(canonicalRgb, Color.fromString(rgb).asRgb()); + assertThat(Color.fromString(rgb).asRgb()).isEqualTo(canonicalRgb); } @Test public void rgbaToRgba() { String rgba = "rgba(1, 2, 3, 0.5)"; - assertEquals("rgba(1, 2, 3, 0.5)", Color.fromString(rgba).asRgba()); + assertThat(Color.fromString(rgba).asRgba()).isEqualTo("rgba(1, 2, 3, 0.5)"); } @Test public void rgbaPctToRgba() { String rgba = "rgba(10%, 20%, 30%, 0.5)"; - assertEquals("rgba(25, 51, 76, 0.5)", Color.fromString(rgba).asRgba()); + assertThat(Color.fromString(rgba).asRgba()).isEqualTo("rgba(25, 51, 76, 0.5)"); } @Test public void hexToHex() { String hex = "#ff00a0"; - assertEquals(hex, Color.fromString(hex).asHex()); + assertThat(Color.fromString(hex).asHex()).isEqualTo(hex); } @Test public void hexToRgb() { String hex = "#01Ff03"; String rgb = "rgb(1, 255, 3)"; - assertEquals(rgb, Color.fromString(hex).asRgb()); + assertThat(Color.fromString(hex).asRgb()).isEqualTo(rgb); } @Test public void hexToRgba() { String hex = "#01Ff03"; String rgba = "rgba(1, 255, 3, 1)"; - assertEquals(rgba, Color.fromString(hex).asRgba()); + assertThat(Color.fromString(hex).asRgba()).isEqualTo(rgba); // same test data as hex3 below hex = "#00ff33"; rgba = "rgba(0, 255, 51, 1)"; - assertEquals(rgba, Color.fromString(hex).asRgba()); + assertThat(Color.fromString(hex).asRgba()).isEqualTo(rgba); } @Test public void rgbToHex() { String hex = "#01ff03"; String rgb = "rgb(1, 255, 3)"; - assertEquals(hex, Color.fromString(rgb).asHex()); + assertThat(Color.fromString(rgb).asHex()).isEqualTo(hex); } @Test public void hex3ToRgba() { String hex = "#0f3"; String rgba = "rgba(0, 255, 51, 1)"; - assertEquals(rgba, Color.fromString(hex).asRgba()); + assertThat(Color.fromString(hex).asRgba()).isEqualTo(rgba); } @Test public void hslToRgba() { String hsl = "hsl(120, 100%, 25%)"; String rgba = "rgba(0, 128, 0, 1)"; - assertEquals(rgba, Color.fromString(hsl).asRgba()); + assertThat(Color.fromString(hsl).asRgba()).isEqualTo(rgba); hsl = "hsl(100, 0%, 50%)"; rgba = "rgba(128, 128, 128, 1)"; - assertEquals(rgba, Color.fromString(hsl).asRgba()); + assertThat(Color.fromString(hsl).asRgba()).isEqualTo(rgba); hsl = "hsl(0, 100%, 50%)"; // red rgba = "rgba(255, 0, 0, 1)"; - assertEquals(rgba, Color.fromString(hsl).asRgba()); + assertThat(Color.fromString(hsl).asRgba()).isEqualTo(rgba); hsl = "hsl(120, 100%, 50%)"; // green rgba = "rgba(0, 255, 0, 1)"; - assertEquals(rgba, Color.fromString(hsl).asRgba()); + assertThat(Color.fromString(hsl).asRgba()).isEqualTo(rgba); hsl = "hsl(240, 100%, 50%)"; // blue rgba = "rgba(0, 0, 255, 1)"; - assertEquals(rgba, Color.fromString(hsl).asRgba()); + assertThat(Color.fromString(hsl).asRgba()).isEqualTo(rgba); hsl = "hsl(0, 0%, 100%)"; // white rgba = "rgba(255, 255, 255, 1)"; - assertEquals(rgba, Color.fromString(hsl).asRgba()); + assertThat(Color.fromString(hsl).asRgba()).isEqualTo(rgba); } @Test public void hslaToRgba() { String hsla = "hsla(120, 100%, 25%, 1)"; String rgba = "rgba(0, 128, 0, 1)"; - assertEquals(rgba, Color.fromString(hsla).asRgba()); + assertThat(Color.fromString(hsla).asRgba()).isEqualTo(rgba); hsla = "hsla(100, 0%, 50%, 0.5)"; rgba = "rgba(128, 128, 128, 0.5)"; - assertEquals(rgba, Color.fromString(hsla).asRgba()); + assertThat(Color.fromString(hsla).asRgba()).isEqualTo(rgba); } @Test public void baseColourToRgba() { String baseColour = "green"; String rgba = "rgba(0, 128, 0, 1)"; - assertEquals(rgba, Color.fromString(baseColour).asRgba()); + assertThat(Color.fromString(baseColour).asRgba()).isEqualTo(rgba); baseColour = "gray"; rgba = "rgba(128, 128, 128, 1)"; - assertEquals(rgba, Color.fromString(baseColour).asRgba()); + assertThat(Color.fromString(baseColour).asRgba()).isEqualTo(rgba); } @Test public void transparentToRgba() { String transparent = "transparent"; String rgba = "rgba(0, 0, 0, 0)"; - assertEquals(rgba, Color.fromString(transparent).asRgba()); + assertThat(Color.fromString(transparent).asRgba()).isEqualTo(rgba); } @Test public void checkEqualsWorks() { Color objectA = Color.fromString("#f00"); Color objectB = Color.fromString("rgb(255, 0, 0)"); - assertEquals(objectA, objectB); + assertThat(objectB).isEqualTo(objectA); } @Test public void checkHashCodeWorks() { Color objectA = Color.fromString("#f00"); Color objectB = Color.fromString("rgb(255, 0, 0)"); - assertEquals(objectA.hashCode(), objectB.hashCode()); + assertThat(objectB.hashCode()).isEqualTo(objectA.hashCode()); } @Test @@ -168,7 +168,7 @@ public void checkSettingOpacityRGB() { actual.setOpacity(0.5); String expected = "rgba(1, 255, 3, 0.5)"; - assertEquals(expected, actual.asRgba()); + assertThat(actual.asRgba()).isEqualTo(expected); } @Test @@ -179,21 +179,21 @@ public void checkSettingOpacityRGBA() { actual.setOpacity(0); String expected = "rgba(1, 255, 3, 0)"; - assertEquals(expected, actual.asRgba()); + assertThat(actual.asRgba()).isEqualTo(expected); } @Test public void baseColourToAwt() { java.awt.Color green = java.awt.Color.GREEN; String rgba = "rgba(0, 255, 0, 1)"; - assertEquals(Color.fromString(rgba).getColor(), green); + assertThat(green).isEqualTo(Color.fromString(rgba).getColor()); } @Test public void transparentColourToAwt() { java.awt.Color transGreen = new java.awt.Color(0, 255, 0, 0); String rgba = "rgba(0, 255, 0, 0)"; - assertEquals(Color.fromString(rgba).getColor(), transGreen); + assertThat(transGreen).isEqualTo(Color.fromString(rgba).getColor()); } } diff --git a/java/client/test/org/openqa/selenium/support/PageFactoryTest.java b/java/client/test/org/openqa/selenium/support/PageFactoryTest.java index d96fb29980659..525951f237441 100644 --- a/java/client/test/org/openqa/selenium/support/PageFactoryTest.java +++ b/java/client/test/org/openqa/selenium/support/PageFactoryTest.java @@ -17,12 +17,8 @@ package org.openqa.selenium.support; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.notNullValue; -import static org.hamcrest.Matchers.nullValue; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -47,21 +43,21 @@ public class PageFactoryTest { public void shouldProxyElementsInAnInstantiatedPage() { PublicPage page = new PublicPage(); - assertThat(page.q, is(nullValue())); - assertThat(page.list, is(nullValue())); + assertThat(page.q).isNull(); + assertThat(page.list).isNull(); PageFactory.initElements(driver, page); - assertThat(page.q, is(notNullValue())); - assertThat(page.list, is(notNullValue())); + assertThat(page.q).isNotNull(); + assertThat(page.list).isNotNull(); } @Test public void shouldInsertProxiesForPublicWebElements() { PublicPage page = PageFactory.initElements(driver, PublicPage.class); - assertThat(page.q, is(notNullValue())); - assertThat(page.list, is(notNullValue())); + assertThat(page.q).isNotNull(); + assertThat(page.list).isNotNull(); } @Test @@ -70,16 +66,16 @@ public void shouldProxyElementsFromParentClassesToo() { PageFactory.initElements(driver, page); - assertThat(page.q, is(notNullValue())); - assertThat(page.list, is(notNullValue())); - assertThat(page.submit, is(notNullValue())); + assertThat(page.q).isNotNull(); + assertThat(page.list).isNotNull(); + assertThat(page.submit).isNotNull(); } @Test public void shouldProxyRenderedWebElementFields() { PublicPage page = PageFactory.initElements(driver, PublicPage.class); - assertThat(page.rendered, is(notNullValue())); + assertThat(page.rendered).isNotNull(); } @Test @@ -88,8 +84,8 @@ public void shouldProxyPrivateElements() { PageFactory.initElements(driver, page); - assertThat(page.getField(), is(notNullValue())); - assertThat(page.getList(), is(notNullValue())); + assertThat(page.getField()).isNotNull(); + assertThat(page.getList()).isNotNull(); } @Test @@ -98,7 +94,7 @@ public void shouldUseAConstructorThatTakesAWebDriverAsAnArgument() { ConstructedPage page = PageFactory.initElements(driver, ConstructedPage.class); - assertThat(driver, equalTo(page.driver)); + assertThat(driver).isEqualTo(page.driver); } @Test @@ -110,7 +106,7 @@ public void shouldNotDecorateFieldsWhenTheFieldDecoratorReturnsNull() { PageFactory.initElements((loader, field) -> null, page); - assertThat(page.q, equalTo(q)); + assertThat(page.q).isEqualTo(q); } @Test @@ -120,7 +116,7 @@ public void triesToDecorateNonWebElements() { PageFactory.initElements((loader, field) -> 5, page); - assertThat(page.num, equalTo(5)); + assertThat(page.num).isEqualTo(5); } @Test @@ -129,7 +125,7 @@ public void shouldNotDecorateListsOfWebElementsThatAreNotAnnotated() { PageFactory.initElements(driver, page); - assertThat(page.elements, is(nullValue())); + assertThat(page.elements).isNull(); } @Test @@ -138,7 +134,7 @@ public void shouldNotDecorateListsThatAreTypedButNotWebElementLists() { PageFactory.initElements(driver, page); - assertThat(page.objects, is(nullValue())); + assertThat(page.objects).isNull(); } @Test @@ -147,31 +143,23 @@ public void shouldNotDecorateUnTypedLists() { PageFactory.initElements(driver, page); - assertThat(page.untyped, is(nullValue())); + assertThat(page.untyped).isNull(); } @Test public void shouldComplainWhenMoreThanOneFindByAttributeIsSet() { GrottyPage page = new GrottyPage(); - try { - PageFactory.initElements((WebDriver) null, page); - fail("Should not have allowed page to be initialised"); - } catch (IllegalArgumentException e) { - // this is expected - } + assertThatExceptionOfType(IllegalArgumentException.class) + .isThrownBy(() -> PageFactory.initElements((WebDriver) null, page)); } @Test public void shouldComplainWhenMoreThanOneFindByShortFormAttributeIsSet() { GrottyPage2 page = new GrottyPage2(); - try { - PageFactory.initElements((WebDriver) null, page); - fail("Should not have allowed page to be initialised"); - } catch (IllegalArgumentException e) { - // this is expected - } + assertThatExceptionOfType(IllegalArgumentException.class) + .isThrownBy(() -> PageFactory.initElements((WebDriver) null, page)); } @Test(expected = TimeoutException.class) diff --git a/java/client/test/org/openqa/selenium/support/ThreadGuardTest.java b/java/client/test/org/openqa/selenium/support/ThreadGuardTest.java index cda1e316d652d..5ca5a5e1790ca 100644 --- a/java/client/test/org/openqa/selenium/support/ThreadGuardTest.java +++ b/java/client/test/org/openqa/selenium/support/ThreadGuardTest.java @@ -16,25 +16,17 @@ // under the License. package org.openqa.selenium.support; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.withSettings; import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.interactions.HasTouchScreen; import java.util.concurrent.atomic.AtomicInteger; -/** - * @author Kristian Rosenvold - */ -@RunWith(JUnit4.class) public class ThreadGuardTest { @Test @@ -48,14 +40,14 @@ public void testProtect() throws Exception { }); foo.start(); foo.join(); - assertEquals(0, successes.get()); + assertThat(successes.get()).isEqualTo(0); } @Test public void testProtectSuccess() { WebDriver actual = mock(WebDriver.class); final WebDriver protect = ThreadGuard.protect(actual); - assertNull(protect.findElement(By.id("foo"))); + assertThat(protect.findElement(By.id("foo"))).isNull(); } @Test @@ -64,6 +56,6 @@ public void testInterfacesProxiedProperly() { withSettings().extraInterfaces(HasTouchScreen.class)); final WebDriver webdriver = ThreadGuard.protect(actual); HasTouchScreen hasTouchScreen = (HasTouchScreen) webdriver; - assertNotNull(hasTouchScreen); + assertThat(hasTouchScreen).isNotNull(); } } diff --git a/java/client/test/org/openqa/selenium/support/events/EventFiringWebDriverTest.java b/java/client/test/org/openqa/selenium/support/events/EventFiringWebDriverTest.java index 5bbc9e2d28e18..ea9fdbf89947c 100644 --- a/java/client/test/org/openqa/selenium/support/events/EventFiringWebDriverTest.java +++ b/java/client/test/org/openqa/selenium/support/events/EventFiringWebDriverTest.java @@ -17,13 +17,10 @@ package org.openqa.selenium.support.events; -import static org.hamcrest.CoreMatchers.*; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.mockito.Mockito.any; +import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; @@ -34,11 +31,7 @@ import com.google.common.collect.ImmutableMap; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; import org.mockito.InOrder; import org.mockito.Mockito; import org.openqa.selenium.Alert; @@ -63,15 +56,8 @@ import java.util.List; import java.util.Map; -/** - * @author Michael Tamm - */ -@RunWith(JUnit4.class) public class EventFiringWebDriverTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); - @Test public void alertEvents() { final WebDriver mockedDriver = mock(WebDriver.class); @@ -259,12 +245,8 @@ public void shouldCallListenersWhenAnExceptionIsThrown() { EventFiringWebDriver testedDriver = new EventFiringWebDriver(mockedDriver).register(listener); - try { - testedDriver.findElement(By.id("foo")); - fail("Expected exception to be propagated"); - } catch (NoSuchElementException e) { - // Fine - } + assertThatExceptionOfType(NoSuchElementException.class) + .isThrownBy(() -> testedDriver.findElement(By.id("foo"))); InOrder order = Mockito.inOrder(mockedDriver, listener); order.verify(listener).beforeFindBy(eq(By.id("foo")), eq(null), any(WebDriver.class)); @@ -302,9 +284,8 @@ public void shouldWrapElementFoundWhenCallingScripts() { Object res = testedDriver.executeScript("foo"); verify((JavascriptExecutor) mockedDriver).executeScript("foo"); - assertThat(res, instanceOf(WebElement.class)); - assertThat(res, instanceOf(WrapsElement.class)); - assertSame(stubbedElement, ((WrapsElement) res).getWrappedElement()); + assertThat(res).isInstanceOf(WebElement.class).isInstanceOf(WrapsElement.class); + assertThat(((WrapsElement) res).getWrappedElement()).isSameAs(stubbedElement); } @Test @@ -319,8 +300,8 @@ public void testShouldUnpackListOfElementArgsWhenCallingScripts() { testedDriver.register(new AbstractWebDriverEventListener() {}); final WebElement foundElement = testedDriver.findElement(By.id("foo")); - assertTrue(foundElement instanceof WrapsElement); - assertSame(mockElement, ((WrapsElement) foundElement).getWrappedElement()); + assertThat(foundElement).isInstanceOf(WrapsElement.class); + assertThat(((WrapsElement) foundElement).getWrappedElement()).isSameAs(mockElement); List args = Arrays.asList("before", foundElement, "after"); @@ -343,11 +324,11 @@ public void shouldWrapMultipleElementsFoundWhenCallingScripts() { Object res = testedDriver.executeScript("foo"); verify((JavascriptExecutor) mockedDriver).executeScript("foo"); - assertThat(res, instanceOf(List.class)); + assertThat(res).isInstanceOf(List.class); List resList = (List) res; - resList.stream().forEach(el -> assertTrue(el instanceof WrapsElement)); - assertSame(stubbedElement1, ((WrapsElement) resList.get(0)).getWrappedElement()); - assertSame(stubbedElement2, ((WrapsElement) resList.get(1)).getWrappedElement()); + resList.forEach(el -> assertThat(el).isInstanceOf(WrapsElement.class)); + assertThat(((WrapsElement) resList.get(0)).getWrappedElement()).isSameAs(stubbedElement1); + assertThat(((WrapsElement) resList.get(1)).getWrappedElement()).isSameAs(stubbedElement2); } @Test @@ -362,8 +343,8 @@ public void shouldWrapMapsWithNullValues() { Object res = testedDriver.executeScript("foo"); verify((JavascriptExecutor) mockedDriver).executeScript("foo"); - assertThat(res, instanceOf(Map.class)); - assertThat(((Map) res).get("a"), is(nullValue())); + assertThat(res).isInstanceOf(Map.class); + assertThat(((Map) res).get("a")).isNull(); } @Test @@ -378,8 +359,8 @@ public void testShouldUnpackMapOfElementArgsWhenCallingScripts() { testedDriver.register(mock(WebDriverEventListener.class)); final WebElement foundElement = testedDriver.findElement(By.id("foo")); - assertTrue(foundElement instanceof WrapsElement); - assertSame(mockElement, ((WrapsElement) foundElement).getWrappedElement()); + assertThat(foundElement).isInstanceOf(WrapsElement.class); + assertThat(((WrapsElement) foundElement).getWrappedElement()).isSameAs(mockElement); ImmutableMap args = ImmutableMap.of( "foo", "bar", @@ -394,13 +375,8 @@ public void testShouldUnpackMapOfElementArgsWhenCallingScripts() { @Test public void shouldBeAbleToWrapSubclassesOfSomethingImplementingTheWebDriverInterface() { - try { - new EventFiringWebDriver(new ChildDriver()); - // We should get this far - } catch (ClassCastException e) { - e.printStackTrace(); - fail("Should have been able to wrap the child of a webdriver implementing interface"); - } + new EventFiringWebDriver(new ChildDriver()); + // We should get this far } @Test @@ -408,14 +384,14 @@ public void shouldBeAbleToAccessWrappedInstanceFromEventCalls() { final WebDriver stub = mock(WebDriver.class); EventFiringWebDriver driver = new EventFiringWebDriver(stub); WebDriver wrapped = driver.getWrappedDriver(); - assertEquals(stub, wrapped); + assertThat(wrapped).isEqualTo(stub); class MyListener extends AbstractWebDriverEventListener { @Override public void beforeNavigateTo(String url, WebDriver driver) { WebDriver unwrapped = ((WrapsDriver) driver).getWrappedDriver(); - assertEquals(stub, unwrapped); + assertThat(unwrapped).isEqualTo(stub); } } @@ -436,7 +412,7 @@ public void shouldBeAbleToAccessWrappedElementInstanceFromEventCalls() { class MyListener extends AbstractWebDriverEventListener { @Override public void beforeClickOn(WebElement element, WebDriver driver) { - assertEquals(stubElement, ((WrapsElement) element).getWrappedElement()); + assertThat(((WrapsElement) element).getWrappedElement()).isEqualTo(stubElement); } } @@ -456,7 +432,7 @@ public void shouldReturnLocatorFromToStringMethod() { EventFiringWebDriver firingDriver = new EventFiringWebDriver(driver); WebElement firingElement = firingDriver.findElement(By.id("ignored")); - assertEquals(stubElement.toString(), firingElement.toString()); + assertThat(firingElement.toString()).isEqualTo(stubElement.toString()); } private static class ChildDriver extends StubDriver {} @@ -468,10 +444,10 @@ public void getScreenshotAs() { WebDriverEventListener listener = mock(WebDriverEventListener.class); EventFiringWebDriver testedDriver = new EventFiringWebDriver(mockedDriver).register(listener); - Mockito.doReturn(DATA).when((TakesScreenshot)mockedDriver).getScreenshotAs(OutputType.BASE64); + doReturn(DATA).when((TakesScreenshot)mockedDriver).getScreenshotAs(OutputType.BASE64); String screenshot = ((TakesScreenshot)testedDriver).getScreenshotAs(OutputType.BASE64); - assertTrue(screenshot.equals(DATA)); + assertThat(screenshot).isEqualTo(DATA); InOrder order = Mockito.inOrder(mockedDriver, listener); order.verify(listener).beforeGetScreenshotAs(OutputType.BASE64); @@ -494,7 +470,7 @@ public void shouldFireEventsAroundGetText() { EventFiringWebDriver testedDriver = new EventFiringWebDriver(mockedDriver).register(listener); String text = testedDriver.findElement(By.name("foo")).getText(); - assertTrue(text.equals(SAMPLE)); + assertThat(text).isEqualTo(SAMPLE); InOrder order = Mockito.inOrder(mockedDriver, mockedElement, listener); order.verify(listener).beforeFindBy(eq(By.name("foo")), eq(null), any(WebDriver.class)); @@ -514,7 +490,7 @@ public void shouldReturnCapabilitiesWhenUnderlyingDriverImplementsInterfac() { final Capabilities caps = new ImmutableCapabilities(); when(((HasCapabilities) mockedDriver).getCapabilities()).thenReturn(caps); - assertSame(caps, testedDriver.getCapabilities()); + assertThat(testedDriver.getCapabilities()).isSameAs(caps); } @Test @@ -522,11 +498,9 @@ public void shouldThrowExceptionWhenUnderlyingDriverDoesNotImplementInterfac() { WebDriver mockedDriver = mock(WebDriver.class); EventFiringWebDriver testedDriver = new EventFiringWebDriver(mockedDriver); - expectedException.expect(UnsupportedOperationException.class); - expectedException.expectMessage(equalTo("Underlying driver does not implement getting" - + " capabilities yet.")); - - testedDriver.getCapabilities(); + assertThatExceptionOfType(UnsupportedOperationException.class) + .isThrownBy(testedDriver::getCapabilities) + .withMessage("Underlying driver does not implement getting capabilities yet."); } } diff --git a/java/client/test/org/openqa/selenium/support/pagefactory/AjaxElementLocatorTest.java b/java/client/test/org/openqa/selenium/support/pagefactory/AjaxElementLocatorTest.java index ed0fd128f8fc7..5b2fde1a9727c 100644 --- a/java/client/test/org/openqa/selenium/support/pagefactory/AjaxElementLocatorTest.java +++ b/java/client/test/org/openqa/selenium/support/pagefactory/AjaxElementLocatorTest.java @@ -17,8 +17,8 @@ package org.openqa.selenium.support.pagefactory; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.mockito.Mockito.atLeast; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; @@ -26,8 +26,6 @@ import static org.mockito.Mockito.when; import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; import org.openqa.selenium.By; import org.openqa.selenium.NoSuchElementException; import org.openqa.selenium.WebDriver; @@ -40,7 +38,6 @@ import java.util.ArrayList; import java.util.List; -@RunWith(JUnit4.class) public class AjaxElementLocatorTest { private FakeClock clock = new FakeClock(); @@ -63,7 +60,7 @@ public void shouldContinueAttemptingToFindElement() throws Exception { ElementLocator locator = newLocator(driver, f); WebElement returnedElement = locator.findElement(); - assertEquals(element, returnedElement); + assertThat(returnedElement).isEqualTo(element); } @Test @@ -82,7 +79,7 @@ public void shouldContinueAttemptingToFindElements() throws Exception { ElementLocator locator = newLocator(driver, f); List returnedList = locator.findElements(); - assertEquals(element, returnedList.get(0)); + assertThat(returnedList.get(0)).isEqualTo(element); } @Test @@ -95,12 +92,8 @@ public void shouldThrowNoSuchElementExceptionIfElementTakesTooLongToAppear() thr ElementLocator locator = new MonkeyedAjaxElementLocator(clock, driver, f, 2); - try { - locator.findElement(); - fail("Should not have located the element"); - } catch (NoSuchElementException e) { - // This is expected - } + assertThatExceptionOfType(NoSuchElementException.class) + .isThrownBy(locator::findElement); // Look ups: // 1. In "isLoaded" @@ -121,12 +114,8 @@ public void shouldAlwaysDoAtLeastOneAttemptAtFindingTheElement() throws Exceptio ElementLocator locator = new MonkeyedAjaxElementLocator(clock, driver, f, 0); - try { - locator.findElement(); - fail("Should not have located the element"); - } catch (NoSuchElementException e) { - // This is expected - } + assertThatExceptionOfType(NoSuchElementException.class) + .isThrownBy(locator::findElement); verify(driver, atLeast(2)).findElement(by); } diff --git a/java/client/test/org/openqa/selenium/support/pagefactory/AnnotationsTest.java b/java/client/test/org/openqa/selenium/support/pagefactory/AnnotationsTest.java index d0723db7e1200..16521300278d2 100644 --- a/java/client/test/org/openqa/selenium/support/pagefactory/AnnotationsTest.java +++ b/java/client/test/org/openqa/selenium/support/pagefactory/AnnotationsTest.java @@ -17,14 +17,10 @@ package org.openqa.selenium.support.pagefactory; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; import org.openqa.selenium.By; import org.openqa.selenium.SearchContext; import org.openqa.selenium.WebElement; @@ -43,7 +39,6 @@ import java.lang.reflect.Field; import java.util.List; -@RunWith(JUnit4.class) public class AnnotationsTest { public WebElement default_field; @@ -132,129 +127,105 @@ public String toString() { @Test public void testDefault() throws Exception { - assertThat(new Annotations(getClass().getField("default_field")).buildBy(), - equalTo((By) new ByIdOrName("default_field"))); + assertThat(new Annotations(getClass().getField("default_field")).buildBy()) + .isEqualTo(new ByIdOrName("default_field")); } @Test public void testDefaultList() throws Exception { - assertThat(new Annotations(getClass().getField("defaultList_field")).buildBy(), - equalTo((By) new ByIdOrName("defaultList_field"))); + assertThat(new Annotations(getClass().getField("defaultList_field")).buildBy()) + .isEqualTo(new ByIdOrName("defaultList_field")); } @Test public void longFindBy() throws Exception { - assertThat(new Annotations(getClass().getField("longFindBy_field")).buildBy(), - equalTo(By.name("cheese"))); + assertThat(new Annotations(getClass().getField("longFindBy_field")).buildBy()) + .isEqualTo(By.name("cheese")); } @Test public void longFindAllBy() throws Exception { - assertThat(new Annotations(getClass().getField("longFindAllBy_field")).buildBy(), - equalTo(By.name("cheese"))); + assertThat(new Annotations(getClass().getField("longFindAllBy_field")).buildBy()) + .isEqualTo(By.name("cheese")); } @Test public void shortFindBy() throws Exception { - assertThat(new Annotations(getClass().getField("shortFindBy_field")).buildBy(), - equalTo(By.name("cheese"))); + assertThat(new Annotations(getClass().getField("shortFindBy_field")).buildBy()) + .isEqualTo(By.name("cheese")); } @Test public void shortFindAllBy() throws Exception { - assertThat(new Annotations(getClass().getField("shortFindAllBy_field")).buildBy(), - equalTo(By.name("cheese"))); + assertThat(new Annotations(getClass().getField("shortFindAllBy_field")).buildBy()) + .isEqualTo(By.name("cheese")); } @Test public void findBys() throws Exception { - assertThat(new Annotations(getClass().getField("findBys_field")).buildBy(), - is(equalTo((By) new ByChained(By.name("cheese"), By.id("fruit"))))); + assertThat(new Annotations(getClass().getField("findBys_field")).buildBy()) + .isEqualTo(new ByChained(By.name("cheese"), By.id("fruit"))); } @Test public void findAll() throws Exception { - assertThat(new Annotations(getClass().getField("findAll_field")).buildBy(), - is(equalTo((By) new ByAll(By.tagName("div"), By.id("fruit"))))); + assertThat(new Annotations(getClass().getField("findAll_field")).buildBy()) + .isEqualTo(new ByAll(By.tagName("div"), By.id("fruit"))); } @Test - public void findByAndFindBys() throws Exception { - try { - new Annotations(getClass().getField("findByAndFindBys_field")).buildBy(); - fail("Expected field annotated with both @FindBy and @FindBys " - + "to throw exception"); - } catch (IllegalArgumentException e) { - // Expected exception - } + public void findByAndFindBys() { + assertThatExceptionOfType(IllegalArgumentException.class) + .describedAs("Expected field annotated with both @FindBy and @FindBys to throw exception") + .isThrownBy(() -> new Annotations(getClass().getField("findByAndFindBys_field")).buildBy()); } @Test - public void findAllAndFindBy() throws Exception { - try { - new Annotations(getClass().getField("findByAndFindBys_field")).buildBy(); - fail("Expected field annotated with both @FindAll and @FindBy " - + "to throw exception"); - } catch (IllegalArgumentException e) { - // Expected exception - } + public void findAllAndFindBy() { + assertThatExceptionOfType(IllegalArgumentException.class) + .describedAs("Expected field annotated with both @FindAll and @FindBy to throw exception") + .isThrownBy(() -> new Annotations(getClass().getField("findByAndFindBys_field")).buildBy()); } @Test - public void findAllAndFindBys() throws Exception { - try { - new Annotations(getClass().getField("findByAndFindBys_field")).buildBy(); - fail("Expected field annotated with both @FindAll and @FindBys " - + "to throw exception"); - } catch (IllegalArgumentException e) { - // Expected exception - } + public void findAllAndFindBys() { + assertThatExceptionOfType(IllegalArgumentException.class) + .describedAs("Expected field annotated with both @FindAll and @FindBys to throw exception") + .isThrownBy(() -> new Annotations(getClass().getField("findByAndFindBys_field")).buildBy()); } @Test - public void findByMultipleHows() throws Exception { - try { - new Annotations(getClass().getField("findByMultipleHows_field")).buildBy(); - fail("Expected field annotated with invalid @FindBy to throw error"); - } catch (IllegalArgumentException e) { - // Expected exception - } + public void findByMultipleHows() { + assertThatExceptionOfType(IllegalArgumentException.class) + .describedAs("Expected field annotated with invalid @FindBy to throw error") + .isThrownBy(() -> new Annotations(getClass().getField("findByMultipleHows_field")).buildBy()); } @Test - public void findAllByMultipleHows() throws Exception { - try { - new Annotations(getClass().getField("findAllByMultipleHows_field")).buildBy(); - fail("Expected field annotated with @FindAllBy containing bad @FindAllBy to throw error"); - } catch (IllegalArgumentException e) { - // Expected exception - } + public void findAllByMultipleHows() { + assertThatExceptionOfType(IllegalArgumentException.class) + .describedAs("Expected field annotated with @FindAllBy containing bad @FindAllBy to throw error") + .isThrownBy(() -> new Annotations(getClass().getField("findAllByMultipleHows_field")).buildBy()); } @Test - public void findBysMultipleHows() throws Exception { - try { - new Annotations(getClass().getField("findBysMultipleHows_field")).buildBy(); - fail("Expected field annotated with @FindBys containing bad @FindBy to throw error"); - } catch (IllegalArgumentException e) { - // Expected exception - } + public void findBysMultipleHows() { + assertThatExceptionOfType(IllegalArgumentException.class) + .describedAs("Expected field annotated with @FindBys containing bad @FindBy to throw error") + .isThrownBy(() -> new Annotations(getClass().getField("findBysMultipleHows_field")).buildBy()); } @Test - public void findAllMultipleHows() throws Exception { - try { - new Annotations(getClass().getField("findAllMultipleHows_field")).buildBy(); - fail("Expected field annotated with @FindAll containing bad @FindBy to throw error"); - } catch (IllegalArgumentException e) { - // Expected exception - } + public void findAllMultipleHows() { + assertThatExceptionOfType(IllegalArgumentException.class) + .describedAs("Expected field annotated with @FindAll containing bad @FindBy to throw error") + .isThrownBy(() -> new Annotations(getClass().getField("findAllMultipleHows_field")).buildBy()); } @Test public void findByUnsetHowIsEquivalentToFindById() throws Exception { - assertThat(new Annotations(getClass().getField("findByUnsetHow_field")).buildBy(), - equalTo(By.id("cheese"))); + assertThat(new Annotations(getClass().getField("findByUnsetHow_field")).buildBy()) + .isEqualTo(By.id("cheese")); } /* @@ -265,8 +236,8 @@ public void findByUnsetHowIsEquivalentToFindById() throws Exception { */ @Test public void findBySomethingElse() throws Exception { - assertThat(new Annotations(getClass().getField("findBy_xxx")).buildBy().toString(), - equalTo("FindByXXXX's By")); + assertThat(new Annotations(getClass().getField("findBy_xxx")).buildBy().toString()) + .isEqualTo("FindByXXXX's By"); } } diff --git a/java/client/test/org/openqa/selenium/support/pagefactory/ByAllTest.java b/java/client/test/org/openqa/selenium/support/pagefactory/ByAllTest.java index 8e20a6ab5bf95..9573a4314e85f 100644 --- a/java/client/test/org/openqa/selenium/support/pagefactory/ByAllTest.java +++ b/java/client/test/org/openqa/selenium/support/pagefactory/ByAllTest.java @@ -17,22 +17,17 @@ package org.openqa.selenium.support.pagefactory; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.instanceOf; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.mockito.Mockito.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; -import static org.openqa.selenium.testing.TestUtilities.catchThrowable; import org.junit.Before; import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; import org.openqa.selenium.By; import org.openqa.selenium.NoSuchElementException; import org.openqa.selenium.WebDriver; @@ -41,7 +36,6 @@ import java.util.ArrayList; import java.util.List; -@RunWith(JUnit4.class) public class ByAllTest { private WebDriver driver; @@ -54,14 +48,14 @@ public void initDriver() { @Test public void findElementZeroBy() { ByAll by = new ByAll(); - Throwable t = catchThrowable(() -> by.findElement(driver)); - assertThat(t, instanceOf(NoSuchElementException.class)); + assertThatExceptionOfType(NoSuchElementException.class) + .isThrownBy(() -> by.findElement(driver)); } @Test public void findElementsZeroBy() { ByAll by = new ByAll(); - assertTrue(by.findElements(driver).isEmpty()); + assertThat(by.findElements(driver).isEmpty()).isTrue(); } @Test @@ -75,7 +69,7 @@ public void findElementOneBy() { when(driver.findElements(By.name("cheese"))).thenReturn(elems12); ByAll by = new ByAll(By.name("cheese")); - assertThat(by.findElement(driver), equalTo(elem1)); + assertThat(by.findElement(driver)).isEqualTo(elem1); } @Test @@ -89,7 +83,7 @@ public void findElementsOneBy() { when(driver.findElements(By.name("cheese"))).thenReturn(elems12); ByAll by = new ByAll(By.name("cheese")); - assertThat(by.findElements(driver), equalTo(elems12)); + assertThat(by.findElements(driver)).isEqualTo(elems12); } @Test @@ -99,8 +93,8 @@ public void findElementOneByEmpty() { when(driver.findElements(By.name("cheese"))).thenReturn(elems); ByAll by = new ByAll(By.name("cheese")); - Throwable t = catchThrowable(() -> by.findElement(driver)); - assertThat(t, instanceOf(NoSuchElementException.class)); + assertThatExceptionOfType(NoSuchElementException.class) + .isThrownBy(() -> by.findElement(driver)); } @Test @@ -108,7 +102,7 @@ public void findElementsOneByEmpty() { when(driver.findElements(By.name("cheese"))).thenReturn(new ArrayList<>()); ByAll by = new ByAll(By.name("cheese")); - assertTrue(by.findElements(driver).isEmpty()); + assertThat(by.findElements(driver)).isEmpty(); } @Test @@ -128,7 +122,7 @@ public void findFourElementBy() { when(driver.findElements(By.name("photo"))).thenReturn(elems34); ByAll by = new ByAll(By.name("cheese"), By.name("photo")); - assertThat(by.findElement(driver), equalTo(elem1)); + assertThat(by.findElement(driver)).isEqualTo(elem1); verify(driver, times(1)).findElements(any(By.class)); verifyNoMoreInteractions(driver); @@ -151,7 +145,7 @@ public void findFourElementByInReverseOrder() { when(driver.findElements(By.name("photo"))).thenReturn(elems34); ByAll by = new ByAll(By.name("photo"), By.name("cheese")); - assertThat(by.findElement(driver), equalTo(elem3)); + assertThat(by.findElement(driver)).isEqualTo(elem3); verify(driver, times(1)).findElements(any(By.class)); verifyNoMoreInteractions(driver); @@ -177,7 +171,7 @@ public void findFourElementsByAny() { when(driver.findElements(By.name("photo"))).thenReturn(elems34); ByAll by = new ByAll(By.name("cheese"), By.name("photo")); - assertThat(by.findElements(driver), equalTo(elems1234)); + assertThat(by.findElements(driver)).isEqualTo(elems1234); verify(driver, times(2)).findElements(any(By.class)); verifyNoMoreInteractions(driver); @@ -203,7 +197,7 @@ public void findFourElementsByAnyInReverseOrder() { when(driver.findElements(By.name("photo"))).thenReturn(elems34); ByAll by = new ByAll(By.name("photo"), By.name("cheese")); - assertThat(by.findElements(driver), equalTo(elems3412)); + assertThat(by.findElements(driver)).isEqualTo(elems3412); verify(driver, times(2)).findElements(any(By.class)); verifyNoMoreInteractions(driver); @@ -211,7 +205,7 @@ public void findFourElementsByAnyInReverseOrder() { @Test public void testEquals() { - assertThat(new ByAll(By.id("cheese"), By.name("photo")), - equalTo(new ByAll(By.id("cheese"), By.name("photo")))); + assertThat(new ByAll(By.id("cheese"), By.name("photo"))) + .isEqualTo(new ByAll(By.id("cheese"), By.name("photo"))); } } diff --git a/java/client/test/org/openqa/selenium/support/pagefactory/ByChainedTest.java b/java/client/test/org/openqa/selenium/support/pagefactory/ByChainedTest.java index 8d0aa3f47ea6c..a1634dd62468e 100644 --- a/java/client/test/org/openqa/selenium/support/pagefactory/ByChainedTest.java +++ b/java/client/test/org/openqa/selenium/support/pagefactory/ByChainedTest.java @@ -17,15 +17,12 @@ package org.openqa.selenium.support.pagefactory; -import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; import org.openqa.selenium.By; import org.openqa.selenium.NoSuchElementException; import org.openqa.selenium.SearchContext; @@ -38,7 +35,6 @@ import java.util.ArrayList; import java.util.List; -@RunWith(JUnit4.class) public class ByChainedTest { @Test @@ -46,12 +42,8 @@ public void findElementZeroBy() { final AllDriver driver = mock(AllDriver.class); ByChained by = new ByChained(); - try { - by.findElement(driver); - fail("Expected NoSuchElementException!"); - } catch (NoSuchElementException e) { - // Expected - } + assertThatExceptionOfType(NoSuchElementException.class) + .isThrownBy(() -> by.findElement(driver)); } @Test @@ -59,8 +51,7 @@ public void findElementsZeroBy() { final AllDriver driver = mock(AllDriver.class); ByChained by = new ByChained(); - assertThat(by.findElements(driver), - equalTo((List) new ArrayList())); + assertThat(by.findElements(driver)).isEqualTo(new ArrayList()); } @Test @@ -75,7 +66,7 @@ public void findElementOneBy() { when(driver.findElementsByName("cheese")).thenReturn(elems12); ByChained by = new ByChained(By.name("cheese")); - assertThat(by.findElement(driver), equalTo(elem1)); + assertThat(by.findElement(driver)).isEqualTo(elem1); } @Test @@ -90,7 +81,7 @@ public void findElementsOneBy() { when(driver.findElementsByName("cheese")).thenReturn(elems12); ByChained by = new ByChained(By.name("cheese")); - assertThat(by.findElements(driver), equalTo(elems12)); + assertThat(by.findElements(driver)).isEqualTo(elems12); } @Test @@ -101,12 +92,8 @@ public void findElementOneByEmpty() { when(driver.findElementsByName("cheese")).thenReturn(elems); ByChained by = new ByChained(By.name("cheese")); - try { - by.findElement(driver); - fail("Expected NoSuchElementException!"); - } catch (NoSuchElementException e) { - // Expected - } + assertThatExceptionOfType(NoSuchElementException.class) + .isThrownBy(() -> by.findElement(driver)); } @Test @@ -117,7 +104,7 @@ public void findElementsOneByEmpty() { when(driver.findElementsByName("cheese")).thenReturn(elems); ByChained by = new ByChained(By.name("cheese")); - assertThat(by.findElements(driver), equalTo(elems)); + assertThat(by.findElements(driver)).isEqualTo(elems); } @Test @@ -145,7 +132,7 @@ public void findElementTwoBy() { when(elem2.findElements(By.name("photo"))).thenReturn(elems5); ByChained by = new ByChained(By.name("cheese"), By.name("photo")); - assertThat(by.findElement(driver), equalTo(elem3)); + assertThat(by.findElement(driver)).isEqualTo(elem3); } @Test @@ -173,12 +160,8 @@ public void findElementTwoByEmptyParent() { when(driver.findElementsByName("cheese")).thenReturn(elems); ByChained by = new ByChained(By.name("cheese"), By.name("photo")); - try { - by.findElement(driver); - fail("Expected NoSuchElementException!"); - } catch (NoSuchElementException e) { - // Expected - } + assertThatExceptionOfType(NoSuchElementException.class) + .isThrownBy(() -> by.findElement(driver)); } @Test @@ -206,7 +189,7 @@ public void findElementsTwoByEmptyParent() { when(driver.findElementsByName("cheese")).thenReturn(elems); ByChained by = new ByChained(By.name("cheese"), By.name("photo")); - assertThat(by.findElements(driver), equalTo(elems)); + assertThat(by.findElements(driver)).isEqualTo(elems); } @Test @@ -236,7 +219,7 @@ public void findElementTwoByEmptyChild() { when(elem2.findElements(By.name("photo"))).thenReturn(elems5); ByChained by = new ByChained(By.name("cheese"), By.name("photo")); - assertThat(by.findElement(driver), equalTo(elem5)); + assertThat(by.findElement(driver)).isEqualTo(elem5); } @Test @@ -266,13 +249,13 @@ public void findElementsTwoByEmptyChild() { when(elem2.findElements(By.name("photo"))).thenReturn(elems5); ByChained by = new ByChained(By.name("cheese"), By.name("photo")); - assertThat(by.findElements(driver), equalTo(elems5)); + assertThat(by.findElements(driver)).isEqualTo(elems5); } @Test public void testEquals() { - assertThat(new ByChained(By.id("cheese"), By.name("photo")), - equalTo(new ByChained(By.id("cheese"), By.name("photo")))); + assertThat(new ByChained(By.id("cheese"), By.name("photo"))) + .isEqualTo(new ByChained(By.id("cheese"), By.name("photo"))); } private interface AllDriver extends diff --git a/java/client/test/org/openqa/selenium/support/pagefactory/DefaultElementLocatorTest.java b/java/client/test/org/openqa/selenium/support/pagefactory/DefaultElementLocatorTest.java index 7b3b39ff540ca..1e01e9395711c 100644 --- a/java/client/test/org/openqa/selenium/support/pagefactory/DefaultElementLocatorTest.java +++ b/java/client/test/org/openqa/selenium/support/pagefactory/DefaultElementLocatorTest.java @@ -17,16 +17,14 @@ package org.openqa.selenium.support.pagefactory; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; import org.openqa.selenium.By; import org.openqa.selenium.NoSuchElementException; import org.openqa.selenium.WebDriver; @@ -40,7 +38,6 @@ import java.util.Arrays; import java.util.List; -@RunWith(JUnit4.class) public class DefaultElementLocatorTest { protected ElementLocator newLocator(WebDriver driver, Field field) { @@ -59,7 +56,7 @@ public void shouldDelegateToDriverInstanceToFindElement() throws Exception { ElementLocator locator = newLocator(driver, f); WebElement returnedElement = locator.findElement(); - assertEquals(element, returnedElement); + assertThat(returnedElement).isEqualTo(element); } @Test @@ -76,7 +73,7 @@ public void shouldDelegateToDriverInstanceToFindElementList() throws Exception { ElementLocator locator = newLocator(driver, f); List returnedList = locator.findElements(); - assertEquals(list, returnedList); + assertThat(returnedList).isEqualTo(list); } @Test @@ -185,15 +182,11 @@ public void shouldNotMaskNoSuchElementExceptionIfThrown() throws Exception { ElementLocator locator = newLocator(driver, f); - try { - locator.findElement(); - fail("Should have allowed the exception to bubble up"); - } catch (NoSuchElementException e) { - // This is expected - } + assertThatExceptionOfType(NoSuchElementException.class) + .isThrownBy(locator::findElement); } - @Test(expected = NullPointerException.class) + @Test public void shouldWorkWithCustomAnnotations() { final WebDriver driver = mock(WebDriver.class); @@ -209,7 +202,8 @@ public By buildBy() { } }; - new DefaultElementLocator(driver, npeAnnotations); + assertThatExceptionOfType(NullPointerException.class) + .isThrownBy(() -> new DefaultElementLocator(driver, npeAnnotations)); } private static class Page { diff --git a/java/client/test/org/openqa/selenium/support/pagefactory/DefaultFieldDecoratorTest.java b/java/client/test/org/openqa/selenium/support/pagefactory/DefaultFieldDecoratorTest.java index bdcbc72c4d443..e7cf942e6c155 100644 --- a/java/client/test/org/openqa/selenium/support/pagefactory/DefaultFieldDecoratorTest.java +++ b/java/client/test/org/openqa/selenium/support/pagefactory/DefaultFieldDecoratorTest.java @@ -17,18 +17,13 @@ package org.openqa.selenium.support.pagefactory; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.notNullValue; -import static org.hamcrest.Matchers.nullValue; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; @@ -48,7 +43,6 @@ import java.util.List; -@RunWith(JUnit4.class) public class DefaultFieldDecoratorTest { // Unusued fields are used by tests. Do not remove! @@ -95,78 +89,62 @@ private FieldDecorator createDecoratorWithDefaultLocator() { public void decoratesWebElement() throws Exception { FieldDecorator decorator = createDecoratorWithDefaultLocator(); assertThat(decorator.decorate(getClass().getClassLoader(), - getClass().getDeclaredField("element1")), - is(notNullValue())); + getClass().getDeclaredField("element1"))).isNotNull(); assertThat(decorator.decorate(getClass().getClassLoader(), - getClass().getDeclaredField("element2")), - is(notNullValue())); + getClass().getDeclaredField("element2"))).isNotNull(); } @Test public void decoratesAnnotatedWebElementList() throws Exception { FieldDecorator decorator = createDecoratorWithDefaultLocator(); assertThat(decorator.decorate(getClass().getClassLoader(), - getClass().getDeclaredField("list3")), - is(notNullValue())); + getClass().getDeclaredField("list3"))).isNotNull(); assertThat(decorator.decorate(getClass().getClassLoader(), - getClass().getDeclaredField("list4")), - is(notNullValue())); + getClass().getDeclaredField("list4"))).isNotNull(); assertThat(decorator.decorate(getClass().getClassLoader(), - getClass().getDeclaredField("list5")), - is(notNullValue())); + getClass().getDeclaredField("list5"))).isNotNull(); } @Test public void doesNotDecorateNonAnnotatedWebElementList() throws Exception { FieldDecorator decorator = createDecoratorWithDefaultLocator(); assertThat(decorator.decorate(getClass().getClassLoader(), - getClass().getDeclaredField("list1")), - is(nullValue())); + getClass().getDeclaredField("list1"))).isNull(); assertThat(decorator.decorate(getClass().getClassLoader(), - getClass().getDeclaredField("list2")), - is(nullValue())); + getClass().getDeclaredField("list2"))).isNull(); } @Test public void doesNotDecorateNonWebElement() throws Exception { FieldDecorator decorator = createDecoratorWithDefaultLocator(); assertThat(decorator.decorate(getClass().getClassLoader(), - getClass().getDeclaredField("num")), - is(nullValue())); + getClass().getDeclaredField("num"))).isNull(); } @Test public void doesNotDecorateListOfSomethingElse() throws Exception { FieldDecorator decorator = createDecoratorWithDefaultLocator(); assertThat(decorator.decorate(getClass().getClassLoader(), - getClass().getDeclaredField("list6")), - is(nullValue())); + getClass().getDeclaredField("list6"))).isNull(); assertThat(decorator.decorate(getClass().getClassLoader(), - getClass().getDeclaredField("list7")), - is(nullValue())); + getClass().getDeclaredField("list7"))).isNull(); assertThat(decorator.decorate(getClass().getClassLoader(), - getClass().getDeclaredField("list8")), - is(nullValue())); + getClass().getDeclaredField("list8"))).isNull(); } @Test public void doesNotDecorateNullLocator() throws Exception { FieldDecorator decorator = createDecoratorWithNullLocator(); assertThat(decorator.decorate(getClass().getClassLoader(), - getClass().getDeclaredField("element1")), - is(nullValue())); + getClass().getDeclaredField("element1"))).isNull(); assertThat(decorator.decorate(getClass().getClassLoader(), - getClass().getDeclaredField("element2")), - is(nullValue())); + getClass().getDeclaredField("element2"))).isNull(); assertThat(decorator.decorate(getClass().getClassLoader(), - getClass().getDeclaredField("list1")), - is(nullValue())); + getClass().getDeclaredField("list1"))).isNull(); assertThat(decorator.decorate(getClass().getClassLoader(), - getClass().getDeclaredField("list2")), - is(nullValue())); + getClass().getDeclaredField("list2"))).isNull(); assertThat(decorator.decorate(getClass().getClassLoader(), - getClass().getDeclaredField("num")), - is(nullValue())); + getClass().getDeclaredField("num"))).isNull(); } @Test diff --git a/java/client/test/org/openqa/selenium/support/pagefactory/UsingPageFactoryTest.java b/java/client/test/org/openqa/selenium/support/pagefactory/UsingPageFactoryTest.java index d7e9212195413..a05933530f08c 100644 --- a/java/client/test/org/openqa/selenium/support/pagefactory/UsingPageFactoryTest.java +++ b/java/client/test/org/openqa/selenium/support/pagefactory/UsingPageFactoryTest.java @@ -17,9 +17,7 @@ package org.openqa.selenium.support.pagefactory; -import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -49,7 +47,7 @@ public void canExecuteJsUsingDecoratedElements() { String tagName = (String) ((JavascriptExecutor) driver).executeScript( "return arguments[0].tagName", page.formElement); - assertEquals("form", tagName.toLowerCase()); + assertThat(tagName).isEqualToIgnoringCase("form"); } @Test @@ -59,9 +57,9 @@ public void canListDecoratedElements() { Page page = new Page(); PageFactory.initElements(driver, page); - assertThat(page.divs.size(), equalTo(13)); + assertThat(page.divs).hasSize(13); for (WebElement link : page.divs) { - assertThat(link.getTagName(), equalTo("div")); + assertThat(link.getTagName()).isEqualTo("div"); } } @@ -79,7 +77,7 @@ public void testDecoratedElementsShouldBeUnwrapped() { Object seen = new WebElementToJsonConverter().apply(page.element); Object expected = new WebElementToJsonConverter().apply(element); - assertEquals(expected, seen); + assertThat(seen).isEqualTo(expected); } diff --git a/java/client/test/org/openqa/selenium/support/pagefactory/internal/LocatingElementHandlerTest.java b/java/client/test/org/openqa/selenium/support/pagefactory/internal/LocatingElementHandlerTest.java index b246b5fcb73ae..01b03ee962755 100644 --- a/java/client/test/org/openqa/selenium/support/pagefactory/internal/LocatingElementHandlerTest.java +++ b/java/client/test/org/openqa/selenium/support/pagefactory/internal/LocatingElementHandlerTest.java @@ -24,8 +24,6 @@ import static org.mockito.Mockito.when; import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; @@ -37,7 +35,6 @@ import java.lang.reflect.Proxy; -@RunWith(JUnit4.class) public class LocatingElementHandlerTest { @Test diff --git a/java/client/test/org/openqa/selenium/support/pagefactory/internal/LocatingElementListHandlerTest.java b/java/client/test/org/openqa/selenium/support/pagefactory/internal/LocatingElementListHandlerTest.java index 7b13d9ae58b2b..074dad9b59d37 100644 --- a/java/client/test/org/openqa/selenium/support/pagefactory/internal/LocatingElementListHandlerTest.java +++ b/java/client/test/org/openqa/selenium/support/pagefactory/internal/LocatingElementListHandlerTest.java @@ -17,8 +17,7 @@ package org.openqa.selenium.support.pagefactory.internal; -import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; @@ -27,8 +26,6 @@ import static org.mockito.Mockito.when; import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; @@ -42,7 +39,6 @@ import java.util.Arrays; import java.util.List; -@RunWith(JUnit4.class) public class LocatingElementListHandlerTest { @SuppressWarnings("unchecked") @@ -61,7 +57,7 @@ public void shouldAlwaysLocateTheElementPerCall() { new Class[] {List.class}, handler); proxy.get(1).sendKeys("Fishy"); - assertThat(proxy.size(), equalTo(2)); + assertThat(proxy).hasSize(2); verify(locator, times(2)).findElements(); verify(element2, times(1)).sendKeys("Fishy"); diff --git a/java/client/test/org/openqa/selenium/support/ui/ExpectedConditionsTest.java b/java/client/test/org/openqa/selenium/support/ui/ExpectedConditionsTest.java index 22c273cf4b3ee..70e81613ca19f 100644 --- a/java/client/test/org/openqa/selenium/support/ui/ExpectedConditionsTest.java +++ b/java/client/test/org/openqa/selenium/support/ui/ExpectedConditionsTest.java @@ -18,12 +18,9 @@ package org.openqa.selenium.support.ui; import static java.time.Instant.EPOCH; -import static java.util.Collections.singletonList; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static java.util.regex.Pattern.compile; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyZeroInteractions; @@ -59,8 +56,6 @@ import org.junit.Before; import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; @@ -76,11 +71,11 @@ import java.time.Instant; import java.util.ArrayList; import java.util.Arrays; +import java.util.Collections; import java.util.List; import java.util.Set; import java.util.regex.Pattern; -@RunWith(JUnit4.class) @SuppressWarnings("unchecked") public class ExpectedConditionsTest { @@ -120,6 +115,7 @@ public void setUpMocks() { public void waitingForUrlToBeOpened_urlToBe() { final String url = "http://some_url"; when(mockDriver.getCurrentUrl()).thenReturn(url); + wait.until(urlToBe(url)); } @@ -127,6 +123,7 @@ public void waitingForUrlToBeOpened_urlToBe() { public void waitingForUrlToBeOpened_urlContains() { final String url = "http://some_url"; when(mockDriver.getCurrentUrl()).thenReturn(url); + wait.until(urlContains("some_url")); } @@ -134,6 +131,7 @@ public void waitingForUrlToBeOpened_urlContains() { public void waitingForUrlToBeOpened_urlMatches() { final String url = "http://some-dynamic:4000/url"; when(mockDriver.getCurrentUrl()).thenReturn(url); + wait.until(urlMatches(".*:\\d{4}\\/url")); } @@ -142,12 +140,8 @@ public void negative_waitingForUrlToBeOpened_urlToBe() { final String url = "http://some_url"; when(mockDriver.getCurrentUrl()).thenReturn(url); - try { - wait.until(urlToBe(url + "/malformed")); - fail(); - } catch (TimeoutException ex) { - // do nothing - } + assertThatExceptionOfType(TimeoutException.class) + .isThrownBy(() -> wait.until(urlToBe(url + "/malformed"))); } @Test @@ -155,12 +149,8 @@ public void negative_waitingForUrlToBeOpened_urlContains() { final String url = "http://some_url"; when(mockDriver.getCurrentUrl()).thenReturn(url); - try { - wait.until(urlContains("/malformed")); - fail(); - } catch (TimeoutException ex) { - // do nothing - } + assertThatExceptionOfType(TimeoutException.class) + .isThrownBy(() -> wait.until(urlContains("/malformed"))); } @Test @@ -168,19 +158,15 @@ public void negative_waitingForUrlToBeOpened_urlMatches() { final String url = "http://some-dynamic:4000/url"; when(mockDriver.getCurrentUrl()).thenReturn(url); - try { - wait.until(urlMatches(".*\\/malformed.*")); - fail(); - } catch (TimeoutException ex) { - // do nothing - } + assertThatExceptionOfType(TimeoutException.class) + .isThrownBy(() -> wait.until(urlMatches(".*\\/malformed.*"))); } @Test public void waitingForVisibilityOfElement_elementAlreadyVisible() { when(mockElement.isDisplayed()).thenReturn(true); - assertSame(mockElement, wait.until(visibilityOf(mockElement))); + assertThat(wait.until(visibilityOf(mockElement))).isSameAs(mockElement); verifyZeroInteractions(mockSleeper); } @@ -188,7 +174,7 @@ public void waitingForVisibilityOfElement_elementAlreadyVisible() { public void waitingForVisibilityOfElement_elementBecomesVisible() throws InterruptedException { when(mockElement.isDisplayed()).thenReturn(false, false, true); - assertSame(mockElement, wait.until(visibilityOf(mockElement))); + assertThat(wait.until(visibilityOf(mockElement))).isSameAs(mockElement); verify(mockSleeper, times(2)).sleep(Duration.ofMillis(250)); } @@ -199,12 +185,8 @@ public void waitingForVisibilityOfElement_elementNeverBecomesVisible() when(mockClock.instant()).thenReturn(EPOCH, EPOCH.plusMillis(500), EPOCH.plusMillis(3000)); when(mockElement.isDisplayed()).thenReturn(false, false); - try { - wait.until(visibilityOf(mockElement)); - fail(); - } catch (TimeoutException expected) { - // Do nothing. - } + assertThatExceptionOfType(TimeoutException.class) + .isThrownBy(() -> wait.until(visibilityOf(mockElement))); verify(mockSleeper, times(1)).sleep(Duration.ofMillis(250)); } @@ -212,7 +194,7 @@ public void waitingForVisibilityOfElement_elementNeverBecomesVisible() public void waitingForVisibilityOfElementInverse_elementNotVisible() { when(mockElement.isDisplayed()).thenReturn(false); - assertTrue(wait.until(not(visibilityOf(mockElement)))); + assertThat(wait.until(not(visibilityOf(mockElement)))).isTrue(); verifyZeroInteractions(mockSleeper); } @@ -220,7 +202,7 @@ public void waitingForVisibilityOfElementInverse_elementNotVisible() { public void booleanExpectationsCanBeNegated() { ExpectedCondition expectation = not(obj -> false); - assertTrue(expectation.apply(mockDriver)); + assertThat(expectation.apply(mockDriver)).isTrue(); } @Test @@ -230,12 +212,8 @@ public void waitingForVisibilityOfElementInverse_elementStaysVisible() when(mockClock.instant()).thenReturn(EPOCH, EPOCH.plusMillis(500), EPOCH.plusMillis(3000)); when(mockElement.isDisplayed()).thenReturn(true, true); - try { - wait.until(not(visibilityOf(mockElement))); - fail(); - } catch (TimeoutException expected) { - // Do nothing. - } + assertThatExceptionOfType(TimeoutException.class) + .isThrownBy(() -> wait.until(not(visibilityOf(mockElement)))); verify(mockSleeper, times(1)).sleep(Duration.ofMillis(250)); } @@ -243,14 +221,14 @@ public void waitingForVisibilityOfElementInverse_elementStaysVisible() public void invertingAConditionThatReturnsFalse() { ExpectedCondition expectation = not(obj -> false); - assertTrue(expectation.apply(mockDriver)); + assertThat(expectation.apply(mockDriver)).isTrue(); } @Test public void invertingAConditionThatReturnsNull() { when(mockCondition.apply(mockDriver)).thenReturn(null); - assertTrue(wait.until(not(mockCondition))); + assertThat(wait.until(not(mockCondition))).isTrue(); verifyZeroInteractions(mockSleeper); } @@ -258,26 +236,26 @@ public void invertingAConditionThatReturnsNull() { public void invertingAConditionThatAlwaysReturnsTrueTimesout() throws InterruptedException { ExpectedCondition expectation = not(obj -> true); - assertFalse(expectation.apply(mockDriver)); + assertThat(expectation.apply(mockDriver)).isFalse(); } @Test public void doubleNegatives_conditionThatReturnsFalseTimesOut() { ExpectedCondition expectation = not(not(obj -> false)); - assertFalse(expectation.apply(mockDriver)); + assertThat(expectation.apply(mockDriver)).isFalse(); } @Test public void doubleNegatives_conditionThatReturnsNull() { ExpectedCondition expectation = not(not(obj -> null)); - assertFalse(expectation.apply(mockDriver)); + assertThat(expectation.apply(mockDriver)).isFalse(); } @Test public void waitingForVisibilityOfAllElementsLocatedByReturnsListOfElements() { - List webElements = singletonList(mockElement); + List webElements = Collections.singletonList(mockElement); String testSelector = "testSelector"; when(mockDriver.findElements(By.cssSelector(testSelector))).thenReturn(webElements); @@ -285,12 +263,12 @@ public void waitingForVisibilityOfAllElementsLocatedByReturnsListOfElements() { List returnedElements = wait.until(visibilityOfAllElementsLocatedBy(By.cssSelector(testSelector))); - assertEquals(webElements, returnedElements); + assertThat(returnedElements).isEqualTo(webElements); } @Test(expected = TimeoutException.class) public void waitingForVisibilityOfAllElementsLocatedByThrowsTimeoutExceptionWhenElementNotDisplayed() { - List webElements = singletonList(mockElement); + List webElements = Collections.singletonList(mockElement); String testSelector = "testSelector"; when(mockDriver.findElements(By.cssSelector(testSelector))).thenReturn(webElements); @@ -301,7 +279,7 @@ public void waitingForVisibilityOfAllElementsLocatedByThrowsTimeoutExceptionWhen @Test(expected = StaleElementReferenceException.class) public void waitingForVisibilityOfAllElementsLocatedByThrowsStaleExceptionWhenElementIsStale() { - List webElements = singletonList(mockElement); + List webElements = Collections.singletonList(mockElement); String testSelector = "testSelector"; when(mockDriver.findElements(By.cssSelector(testSelector))).thenReturn(webElements); @@ -322,16 +300,16 @@ public void waitingForVisibilityOfAllElementsLocatedByThrowsTimeoutExceptionWhen @Test public void waitingForVisibilityOfAllElementsReturnsListOfElements() { - List webElements = singletonList(mockElement); + List webElements = Collections.singletonList(mockElement); when(mockElement.isDisplayed()).thenReturn(true); List returnedElements = wait.until(visibilityOfAllElements(webElements)); - assertEquals(webElements, returnedElements); + assertThat(returnedElements).isEqualTo(webElements); } @Test(expected = TimeoutException.class) public void waitingForVisibilityOfAllElementsThrowsTimeoutExceptionWhenElementNotDisplayed() { - List webElements = singletonList(mockElement); + List webElements = Collections.singletonList(mockElement); when(mockElement.isDisplayed()).thenReturn(false); wait.until(visibilityOfAllElements(webElements)); @@ -339,7 +317,7 @@ public void waitingForVisibilityOfAllElementsThrowsTimeoutExceptionWhenElementNo @Test(expected = StaleElementReferenceException.class) public void waitingForVisibilityOfAllElementsThrowsStaleElementReferenceExceptionWhenElementIsStale() { - List webElements = singletonList(mockElement); + List webElements = Collections.singletonList(mockElement); when(mockElement.isDisplayed()).thenThrow(new StaleElementReferenceException("Stale element")); @@ -358,7 +336,7 @@ public void waitingForVisibilityOfReturnsElement() { when(mockElement.isDisplayed()).thenReturn(true); WebElement returnedElement = wait.until(visibilityOf(mockElement)); - assertEquals(mockElement, returnedElement); + assertThat(returnedElement).isEqualTo(mockElement); } @Test(expected = TimeoutException.class) @@ -383,8 +361,9 @@ public void waitingForTextToBePresentInElementLocatedReturnsElement() { when(mockDriver.findElements(By.cssSelector(testSelector))).thenReturn(Arrays.asList(mockElement)); when(mockElement.getText()).thenReturn("testText"); - assertTrue( - wait.until(textToBePresentInElementLocated(By.cssSelector(testSelector), "testText"))); + assertThat( + wait.until(textToBePresentInElementLocated(By.cssSelector(testSelector), "testText"))) + .isTrue(); } @Test @@ -393,7 +372,8 @@ public void waitingForTextToBePresentInElementLocatedReturnsElementWhenTextConta when(mockDriver.findElements(By.cssSelector(testSelector))).thenReturn(Arrays.asList(mockElement)); when(mockElement.getText()).thenReturn("testText"); - assertTrue(wait.until(textToBePresentInElementLocated(By.cssSelector(testSelector), "test"))); + assertThat(wait.until(textToBePresentInElementLocated(By.cssSelector(testSelector), "test"))) + .isTrue(); } @Test @@ -405,9 +385,8 @@ public void waitingForHtmlAttributeToBeEqualForElementLocatedReturnsTrueWhenAttr when(mockElement.getAttribute(attributeName)).thenReturn(attributeValue); when(mockElement.getCssValue(attributeName)).thenReturn(""); - assertTrue( - wait.until( - ExpectedConditions.attributeToBe(By.cssSelector(testSelector), attributeName, attributeValue))); + assertThat(wait.until( + attributeToBe(By.cssSelector(testSelector), attributeName, attributeValue))).isTrue(); } @Test @@ -419,9 +398,8 @@ public void waitingForCssAttributeToBeEqualForElementLocatedReturnsTrueWhenAttri when(mockElement.getAttribute(attributeName)).thenReturn(""); when(mockElement.getCssValue(attributeName)).thenReturn(attributeValue); - assertTrue( - wait.until( - ExpectedConditions.attributeToBe(By.cssSelector(testSelector), attributeName, attributeValue))); + assertThat(wait.until( + attributeToBe(By.cssSelector(testSelector), attributeName, attributeValue))).isTrue(); } @Test(expected = TimeoutException.class) @@ -442,8 +420,7 @@ public void waitingForHtmlAttributeToBeEqualForWebElementReturnsTrueWhenAttribut when(mockElement.getAttribute(attributeName)).thenReturn(attributeValue); when(mockElement.getCssValue(attributeName)).thenReturn(""); - assertTrue( - wait.until(attributeToBe(mockElement, attributeName, attributeValue))); + assertThat(wait.until(attributeToBe(mockElement, attributeName, attributeValue))).isTrue(); } @Test @@ -453,8 +430,7 @@ public void waitingForCssAttributeToBeEqualForWebElementReturnsTrueWhenAttribute when(mockElement.getAttribute(attributeName)).thenReturn(""); when(mockElement.getCssValue(attributeName)).thenReturn(attributeValue); - assertTrue( - wait.until(attributeToBe(mockElement, attributeName, attributeValue))); + assertThat(wait.until(attributeToBe(mockElement, attributeName, attributeValue))).isTrue(); } @Test(expected = TimeoutException.class) @@ -475,8 +451,8 @@ public void waitingForHtmlAttributeToBeEqualForElementLocatedReturnsTrueWhenAttr when(mockElement.getAttribute(attributeName)).thenReturn(attributeValue); when(mockElement.getCssValue(attributeName)).thenReturn(""); - assertTrue( - wait.until(attributeContains(By.cssSelector(testSelector), attributeName, "attributeValue"))); + assertThat(wait.until( + attributeContains(By.cssSelector(testSelector), attributeName, "attributeValue"))).isTrue(); } @Test @@ -488,15 +464,15 @@ public void waitingForCssAttributeToBeEqualForElementLocatedReturnsTrueWhenAttri when(mockElement.getAttribute(attributeName)).thenReturn(""); when(mockElement.getCssValue(attributeName)).thenReturn(attributeValue); - assertTrue( - wait.until(attributeContains(By.cssSelector(testSelector), attributeName, "attributeValue"))); + assertThat(wait.until( + attributeContains(By.cssSelector(testSelector), attributeName, "attributeValue"))).isTrue(); } @Test(expected = TimeoutException.class) public void waitingForCssAttributeToBeEqualForElementLocatedThrowsTimeoutExceptionWhenAttributeContainsNotEqual() { By parent = By.cssSelector("parent"); String attributeName = "attributeName"; - when(mockDriver.findElements(parent)).thenReturn(singletonList(mockElement)); + when(mockDriver.findElements(parent)).thenReturn(Collections.singletonList(mockElement)); when(mockElement.getAttribute(attributeName)).thenReturn(""); when(mockElement.getCssValue(attributeName)).thenReturn(""); @@ -510,8 +486,8 @@ public void waitingForHtmlAttributeToBeEqualForWebElementReturnsTrueWhenAttribut when(mockElement.getAttribute(attributeName)).thenReturn(attributeValue); when(mockElement.getCssValue(attributeName)).thenReturn(""); - assertTrue( - wait.until(attributeContains(mockElement, attributeName, "attributeValue"))); + assertThat(wait.until(attributeContains(mockElement, attributeName, "attributeValue"))) + .isTrue(); } @Test @@ -521,8 +497,8 @@ public void waitingForCssAttributeToBeEqualForWebElementReturnsTrueWhenAttribute when(mockElement.getAttribute(attributeName)).thenReturn(""); when(mockElement.getCssValue(attributeName)).thenReturn(attributeValue); - assertTrue( - wait.until(attributeContains(mockElement, attributeName, "attributeValue"))); + assertThat(wait.until(attributeContains(mockElement, attributeName, "attributeValue"))) + .isTrue(); } @Test(expected = TimeoutException.class) @@ -541,8 +517,7 @@ public void waitingForTextToBeEqualForElementLocatedReturnsTrueWhenTextIsEqualTo when(mockDriver.findElements(By.cssSelector(testSelector))).thenReturn(Arrays.asList(mockElement)); when(mockElement.getText()).thenReturn(testText); - assertTrue( - wait.until(textToBe(By.cssSelector(testSelector), testText))); + assertThat(wait.until(textToBe(By.cssSelector(testSelector), testText))).isTrue(); } @Test @@ -551,7 +526,7 @@ public void waitingForAttributeToBeNotEmptyForElementLocatedReturnsTrueWhenAttri when(mockElement.getAttribute(attributeName)).thenReturn(""); when(mockElement.getCssValue(attributeName)).thenReturn("test1"); - assertTrue(wait.until(attributeToBeNotEmpty(mockElement, attributeName))); + assertThat(wait.until(attributeToBeNotEmpty(mockElement, attributeName))).isTrue(); } @Test @@ -560,7 +535,7 @@ public void waitingForAttributeToBeNotEmptyForElementLocatedReturnsTrueWhenAttri when(mockElement.getAttribute(attributeName)).thenReturn("test1"); when(mockElement.getCssValue(attributeName)).thenReturn(""); - assertTrue(wait.until(attributeToBeNotEmpty(mockElement, attributeName))); + assertThat(wait.until(attributeToBeNotEmpty(mockElement, attributeName))).isTrue(); } @Test(expected = TimeoutException.class) @@ -596,8 +571,8 @@ public void waitForOneOfExpectedConditionsToHavePositiveResultWhenFirstPositive( when(mockElement.getCssValue(attributeName)).thenReturn(attributeName); when(mockElement.getText()).thenReturn(""); - assertTrue(wait.until(or(attributeToBe(mockElement, attributeName, attributeName), - textToBePresentInElement(mockElement, attributeName)))); + assertThat(wait.until(or(attributeToBe(mockElement, attributeName, attributeName), + textToBePresentInElement(mockElement, attributeName)))).isTrue(); } @Test @@ -607,8 +582,8 @@ public void waitForOneOfExpectedConditionsToHavePositiveResultWhenAllPositive() when(mockElement.getCssValue(attributeName)).thenReturn(attributeName); when(mockElement.getText()).thenReturn(attributeName); - assertTrue(wait.until(or(attributeToBe(mockElement, attributeName, attributeName), - textToBePresentInElement(mockElement, attributeName)))); + assertThat(wait.until(or(attributeToBe(mockElement, attributeName, attributeName), + textToBePresentInElement(mockElement, attributeName)))).isTrue(); } @Test @@ -618,8 +593,8 @@ public void waitForOneOfExpectedConditionsToHavePositiveResultWhenSecondPositive when(mockElement.getCssValue(attributeName)).thenReturn(attributeName); when(mockElement.getText()).thenReturn(""); - assertTrue(wait.until(or(textToBePresentInElement(mockElement, attributeName), - attributeToBe(mockElement, attributeName, attributeName)))); + assertThat(wait.until(or(textToBePresentInElement(mockElement, attributeName), + attributeToBe(mockElement, attributeName, attributeName)))).isTrue(); } @Test @@ -629,8 +604,8 @@ public void waitForOneOfExpectedConditionsToHavePositiveResultWhenOneThrows() { when(mockElement.getCssValue(attributeName)).thenReturn(attributeName); when(mockElement.getText()).thenThrow(new NoSuchElementException("")); - assertTrue(wait.until(or(textToBePresentInElement(mockElement, attributeName), - attributeToBe(mockElement, attributeName, attributeName)))); + assertThat(wait.until(or(textToBePresentInElement(mockElement, attributeName), + attributeToBe(mockElement, attributeName, attributeName)))).isTrue(); } @Test(expected = NoSuchElementException.class) @@ -681,8 +656,8 @@ public void waitingForAllExpectedConditionsToHavePositiveResultWhenAllPositive() when(mockElement.getText()).thenReturn(attributeName); when(mockElement.getCssValue(attributeName)).thenReturn(attributeName); when(mockElement.getAttribute(attributeName)).thenReturn(attributeName); - assertTrue(wait.until(and(textToBePresentInElement(mockElement, attributeName), - attributeToBe(mockElement, attributeName, attributeName)))); + assertThat(wait.until(and(textToBePresentInElement(mockElement, attributeName), + attributeToBe(mockElement, attributeName, attributeName)))).isTrue(); } @Test @@ -690,7 +665,8 @@ public void waitingForTextMatchingPatternWhenTextExists() { String testSelector = "testSelector"; when(mockDriver.findElements(By.cssSelector(testSelector))).thenReturn(Arrays.asList(mockElement)); when(mockElement.getText()).thenReturn("123"); - assertTrue(wait.until(textMatches(By.cssSelector(testSelector), Pattern.compile("\\d")))); + assertThat(wait.until(textMatches(By.cssSelector(testSelector), compile("\\d")))) + .isTrue(); } @Test(expected = TimeoutException.class) @@ -714,7 +690,8 @@ public void waitingForSpecificNumberOfElementsMoreThanSpecifiedPositive() { String testSelector = "testSelector"; when(mockDriver.findElements(By.cssSelector(testSelector))) .thenReturn(Arrays.asList(mockElement, mockElement)); - assertEquals(2, wait.until(numberOfElementsToBeMoreThan(By.cssSelector(testSelector), 1)).size()); + assertThat(wait.until(numberOfElementsToBeMoreThan(By.cssSelector(testSelector), 1)).size()) + .isEqualTo(2); } @Test(expected = TimeoutException.class) @@ -730,7 +707,8 @@ public void waitingForSpecificNumberOfElementsLessThanSpecifiedPositive() { String testSelector = "testSelector"; when(mockDriver.findElements(By.cssSelector(testSelector))) .thenReturn(Arrays.asList(mockElement)); - assertEquals(1, wait.until(numberOfElementsToBeLessThan(By.cssSelector(testSelector), 2)).size()); + assertThat(wait.until(numberOfElementsToBeLessThan(By.cssSelector(testSelector), 2)).size()) + .isEqualTo(1); } @Test @@ -738,7 +716,8 @@ public void waitingForSpecificNumberOfElementsPositive() { String testSelector = "testSelector"; when(mockDriver.findElements(By.cssSelector(testSelector))) .thenReturn(Arrays.asList(mockElement, mockElement)); - assertEquals(2, wait.until(numberOfElementsToBe(By.cssSelector(testSelector), 2)).size()); + assertThat(wait.until(numberOfElementsToBe(By.cssSelector(testSelector), 2)).size()) + .isEqualTo(2); } @Test(expected = TimeoutException.class) @@ -795,19 +774,19 @@ public void waitingForPresenseOfNestedElementsWhenElementsPresent() { By parent = By.cssSelector("parent"); By child = By.cssSelector("child"); - when(mockDriver.findElements(parent)).thenReturn(singletonList(mockElement)); - when(mockElement.findElements(child)).thenReturn(singletonList(mockNestedElement)); + when(mockDriver.findElements(parent)).thenReturn(Collections.singletonList(mockElement)); + when(mockElement.findElements(child)).thenReturn(Collections.singletonList(mockNestedElement)); List elements = wait.until( presenceOfNestedElementsLocatedBy(parent, child)); - assertEquals(elements.get(0), mockNestedElement); + assertThat(mockNestedElement).isEqualTo(elements.get(0)); } @Test public void waitingForAllElementsInvisibility() { when(mockElement.isDisplayed()).thenReturn(false); - assertTrue(wait.until(invisibilityOfAllElements(Arrays.asList(mockElement)))); + assertThat(wait.until(invisibilityOfAllElements(Arrays.asList(mockElement)))).isTrue(); } @Test(expected = TimeoutException.class) @@ -853,14 +832,14 @@ public void waitingTextToBePresentInElementLocatedThrowsTimeoutExceptionWhenNoEl public void waitingElementSelectionStateToBeTrueReturnsTrue() { when(mockElement.isSelected()).thenReturn(true); - assertTrue(wait.until(elementSelectionStateToBe(mockElement, true))); + assertThat(wait.until(elementSelectionStateToBe(mockElement, true))).isTrue(); } @Test public void waitingElementSelectionStateToBeFalseReturnsTrue() { when(mockElement.isSelected()).thenReturn(false); - assertTrue(wait.until(elementSelectionStateToBe(mockElement, false))); + assertThat(wait.until(elementSelectionStateToBe(mockElement, false))).isTrue(); } @Test(expected = TimeoutException.class) @@ -883,7 +862,7 @@ public void waitingNumberOfWindowsToBeTwoWhenThereAreTwoWindowsOpen() { Set twoWindowHandles = Sets.newHashSet("w1", "w2"); when(mockDriver.getWindowHandles()).thenReturn(twoWindowHandles); - assertTrue(wait.until(numberOfWindowsToBe(2))); + assertThat(wait.until(numberOfWindowsToBe(2))).isTrue(); } @Test(expected = TimeoutException.class) diff --git a/java/client/test/org/openqa/selenium/support/ui/FluentWaitTest.java b/java/client/test/org/openqa/selenium/support/ui/FluentWaitTest.java index 7eed95dd27484..68793cc786ca3 100644 --- a/java/client/test/org/openqa/selenium/support/ui/FluentWaitTest.java +++ b/java/client/test/org/openqa/selenium/support/ui/FluentWaitTest.java @@ -18,18 +18,14 @@ package org.openqa.selenium.support.ui; import static java.time.Instant.EPOCH; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import org.junit.Before; import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.openqa.selenium.NoSuchElementException; @@ -41,7 +37,6 @@ import java.time.Duration; import java.util.function.Function; -@RunWith(JUnit4.class) public class FluentWaitTest { private static final Object ARBITRARY_VALUE = new Object(); @@ -70,7 +65,7 @@ public void shouldWaitUntilReturnValueOfConditionIsNotNull() throws InterruptedE .pollingEvery(Duration.ofSeconds(2)) .ignoring(NoSuchElementException.class, NoSuchFrameException.class); - assertEquals(ARBITRARY_VALUE, wait.until(mockCondition)); + assertThat(wait.until(mockCondition)).isEqualTo(ARBITRARY_VALUE); verify(mockSleeper, times(1)).sleep(Duration.ofSeconds(2)); } @@ -82,9 +77,9 @@ public void shouldWaitUntilABooleanResultIsTrue() throws InterruptedException { Wait wait = new FluentWait<>(mockDriver, mockClock, mockSleeper) .withTimeout(Duration.ofMillis(0)) .pollingEvery(Duration.ofSeconds(2)) - .ignoring(NoSuchElementException.class, NoSuchFrameException.class); + .ignoring(NoSuchElementException.class, NoSuchFrameException.class); - assertEquals(true, wait.until(mockCondition)); + assertThat(wait.until(mockCondition)).isEqualTo(true); verify(mockSleeper, times(2)).sleep(Duration.ofSeconds(2)); } @@ -96,12 +91,9 @@ public void checksTimeoutAfterConditionSoZeroTimeoutWaitsCanSucceed() { Wait wait = new FluentWait<>(mockDriver, mockClock, mockSleeper) .withTimeout(Duration.ofMillis(0)); - try { - wait.until(mockCondition); - fail(); - } catch (TimeoutException expected) { - assertNull(expected.getCause()); - } + assertThatExceptionOfType(TimeoutException.class) + .isThrownBy(() -> wait.until(mockCondition)) + .withNoCause(); } @Test @@ -117,7 +109,7 @@ public void canIgnoreMultipleExceptions() throws InterruptedException { .pollingEvery(Duration.ofSeconds(2)) .ignoring(NoSuchElementException.class, NoSuchFrameException.class); - assertEquals(ARBITRARY_VALUE, wait.until(mockCondition)); + assertThat(wait.until(mockCondition)).isEqualTo(ARBITRARY_VALUE); verify(mockSleeper, times(2)).sleep(Duration.ofSeconds(2)); } @@ -134,12 +126,9 @@ public void propagatesUnIgnoredExceptions() { .pollingEvery(Duration.ofSeconds(2)) .ignoring(NoSuchElementException.class, NoSuchFrameException.class); - try { - wait.until(mockCondition); - fail(); - } catch (NoSuchWindowException expected) { - assertSame(exception, expected); - } + assertThatExceptionOfType(NoSuchWindowException.class) + .isThrownBy(() -> wait.until(mockCondition)) + .satisfies(expected -> assertThat(expected).isSameAs(exception)); } @Test @@ -155,17 +144,15 @@ public void timeoutMessageIncludesLastIgnoredException() { .withTimeout(Duration.ofMillis(0)) .pollingEvery(Duration.ofSeconds(2)) .ignoring(NoSuchWindowException.class); - try { - wait.until(mockCondition); - fail(); - } catch (TimeoutException expected) { - assertSame(exception, expected.getCause()); - } + + assertThatExceptionOfType(TimeoutException.class) + .isThrownBy(() -> wait.until(mockCondition)) + .satisfies(expected -> assertThat(exception).isSameAs(expected.getCause())); } @Test public void timeoutMessageIncludesCustomMessage() { - TimeoutException expected = new TimeoutException( + TimeoutException exception = new TimeoutException( "Expected condition failed: Expected custom timeout message " + "(tried for 0 second(s) with 500 milliseconds interval)"); @@ -176,19 +163,16 @@ public void timeoutMessageIncludesCustomMessage() { .withTimeout(Duration.ofMillis(0)) .withMessage("Expected custom timeout message"); - try { - wait.until(mockCondition); - fail(); - } catch (TimeoutException actual) { - assertEquals(expected.getMessage(), actual.getMessage()); - } + assertThatExceptionOfType(TimeoutException.class) + .isThrownBy(() -> wait.until(mockCondition)) + .withMessage(exception.getMessage()); } private String state = null; @Test public void timeoutMessageIncludesCustomMessageEvaluatedOnFailure() { - TimeoutException expected = new TimeoutException( + TimeoutException exception = new TimeoutException( "Expected condition failed: external state " + "(tried for 0 second(s) with 500 milliseconds interval)"); @@ -201,17 +185,14 @@ public void timeoutMessageIncludesCustomMessageEvaluatedOnFailure() { state = "external state"; - try { - wait.until(mockCondition); - fail(); - } catch (TimeoutException actual) { - assertEquals(expected.getMessage(), actual.getMessage()); - } + assertThatExceptionOfType(TimeoutException.class) + .isThrownBy(() -> wait.until(mockCondition)) + .withMessage(exception.getMessage()); } @Test public void timeoutMessageIncludesToStringOfCondition() { - TimeoutException expected = new TimeoutException( + TimeoutException exception = new TimeoutException( "Expected condition failed: waiting for toString called " + "(tried for 0 second(s) with 500 milliseconds interval)"); @@ -229,12 +210,9 @@ public String toString() { Wait wait = new FluentWait("cheese") .withTimeout(Duration.ofMillis(0)); - try { - wait.until(condition); - fail(); - } catch (TimeoutException actual) { - assertEquals(expected.getMessage(), actual.getMessage()); - } + assertThatExceptionOfType(TimeoutException.class) + .isThrownBy(() -> wait.until(condition)) + .withMessage(exception.getMessage()); } @Test @@ -249,12 +227,9 @@ public void canIgnoreThrowables() { .pollingEvery(Duration.ofSeconds(2)) .ignoring(AssertionError.class); - try { - wait.until(mockCondition); - fail(); - } catch (TimeoutException expected) { - assertSame(exception, expected.getCause()); - } + assertThatExceptionOfType(TimeoutException.class) + .isThrownBy(() -> wait.until(mockCondition)) + .satisfies(expected -> assertThat(exception).isSameAs(expected.getCause())); } @Test @@ -274,19 +249,12 @@ protected RuntimeException timeoutException(String message, Throwable lastExcept .pollingEvery(Duration.ofSeconds(2)) .ignoring(TimeoutException.class); - try { - wait.until(mockCondition); - fail(); - } catch (TestException expected) { - assertSame(sentinelException, expected); - } + assertThatExceptionOfType(TestException.class) + .isThrownBy(() -> wait.until(mockCondition)) + .satisfies(expected -> assertThat(sentinelException).isSameAs(expected)); } private static class TestException extends RuntimeException { } - - public interface GenericCondition extends ExpectedCondition { - - } } diff --git a/java/client/test/org/openqa/selenium/support/ui/HowTest.java b/java/client/test/org/openqa/selenium/support/ui/HowTest.java index 1541fdca21188..14522d4a94ef3 100644 --- a/java/client/test/org/openqa/selenium/support/ui/HowTest.java +++ b/java/client/test/org/openqa/selenium/support/ui/HowTest.java @@ -17,7 +17,7 @@ package org.openqa.selenium.support.ui; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; import org.openqa.selenium.By; @@ -30,52 +30,53 @@ public class HowTest { @Test public void testBuildByClassName(){ - assertEquals(By.className(VALUE).toString(), How.CLASS_NAME.buildBy(VALUE).toString()); + assertThat(How.CLASS_NAME.buildBy(VALUE).toString()).isEqualTo(By.className(VALUE).toString()); } @Test public void testBuildByCss(){ - assertEquals(By.cssSelector(VALUE).toString(), How.CSS.buildBy(VALUE).toString()); + assertThat(How.CSS.buildBy(VALUE).toString()).isEqualTo(By.cssSelector(VALUE).toString()); } @Test public void testBuildById(){ - assertEquals(By.id(VALUE).toString(), How.ID.buildBy(VALUE).toString()); + assertThat(How.ID.buildBy(VALUE).toString()).isEqualTo(By.id(VALUE).toString()); } @Test public void testBuildByIdOrName(){ - assertEquals(new ByIdOrName(VALUE).toString(), How.ID_OR_NAME.buildBy(VALUE).toString()); + assertThat(How.ID_OR_NAME.buildBy(VALUE).toString()) + .isEqualTo(new ByIdOrName(VALUE).toString()); } @Test public void testBuildByLinkText(){ - assertEquals(By.linkText(VALUE).toString(), How.LINK_TEXT.buildBy(VALUE).toString()); + assertThat(How.LINK_TEXT.buildBy(VALUE).toString()).isEqualTo(By.linkText(VALUE).toString()); } @Test public void testBuildByName(){ - assertEquals(By.name(VALUE).toString(), How.NAME.buildBy(VALUE).toString()); + assertThat(How.NAME.buildBy(VALUE).toString()).isEqualTo(By.name(VALUE).toString()); } @Test public void testBuildByPartialLinkText(){ - assertEquals(By.partialLinkText(VALUE).toString(), - How.PARTIAL_LINK_TEXT.buildBy(VALUE).toString()); + assertThat(How.PARTIAL_LINK_TEXT.buildBy(VALUE).toString()) + .isEqualTo(By.partialLinkText(VALUE).toString()); } @Test public void testBuildByTagName(){ - assertEquals(By.tagName(VALUE).toString(), How.TAG_NAME.buildBy(VALUE).toString()); + assertThat(How.TAG_NAME.buildBy(VALUE).toString()).isEqualTo(By.tagName(VALUE).toString()); } @Test public void testBuildByXpath(){ - assertEquals(By.xpath(VALUE).toString(), How.XPATH.buildBy(VALUE).toString()); + assertThat(How.XPATH.buildBy(VALUE).toString()).isEqualTo(By.xpath(VALUE).toString()); } @Test public void testBuildUnset(){ - assertEquals(By.id(VALUE).toString(), How.UNSET.buildBy(VALUE).toString()); + assertThat(How.UNSET.buildBy(VALUE).toString()).isEqualTo(By.id(VALUE).toString()); } } diff --git a/java/client/test/org/openqa/selenium/support/ui/LoadableComponentTest.java b/java/client/test/org/openqa/selenium/support/ui/LoadableComponentTest.java index daa4042729bde..3fea35ceef193 100644 --- a/java/client/test/org/openqa/selenium/support/ui/LoadableComponentTest.java +++ b/java/client/test/org/openqa/selenium/support/ui/LoadableComponentTest.java @@ -17,23 +17,15 @@ package org.openqa.selenium.support.ui; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; -@RunWith(JUnit4.class) public class LoadableComponentTest { @Test public void testShouldDoNothingIfComponentIsAlreadyLoaded() { - try { - new DetonatingComponent().get(); - } catch (RuntimeException e) { - fail("Should not have called the load method"); - } + new DetonatingComponent().get(); } @Test @@ -42,19 +34,16 @@ public void testShouldCauseTheLoadMethodToBeCalledIfTheComponentIsNotAlreadyLoad ok.get(); - assertTrue(ok.wasLoadCalled()); + assertThat(ok.wasLoadCalled()).isTrue(); } @Test public void testShouldThrowAnErrorIfCallingLoadDoesNotCauseTheComponentToLoad() { LoadsOk ok = new LoadsOk(false); - try { - ok.get(); - fail(); - } catch (Error e) { - assertEquals("Expected failure", e.getMessage()); - } + assertThatExceptionOfType(Error.class) + .isThrownBy(ok::get) + .withMessage("Expected failure"); } private static class DetonatingComponent extends LoadableComponent { diff --git a/java/client/test/org/openqa/selenium/support/ui/QuotesTest.java b/java/client/test/org/openqa/selenium/support/ui/QuotesTest.java index c297d22b9559d..66f70496662cb 100644 --- a/java/client/test/org/openqa/selenium/support/ui/QuotesTest.java +++ b/java/client/test/org/openqa/selenium/support/ui/QuotesTest.java @@ -17,32 +17,30 @@ package org.openqa.selenium.support.ui; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; +import static org.openqa.selenium.support.ui.Quotes.escape; import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; -@RunWith(JUnit4.class) public class QuotesTest { @Test public void shouldConvertAnUnquotedStringIntoOneWithQuotes() { - assertEquals("\"foo\"", Quotes.escape("foo")); + assertThat(escape("foo")).isEqualTo("\"foo\""); } @Test public void shouldConvertAStringWithATickIntoOneWithQuotes() { - assertEquals("\"f'oo\"", Quotes.escape("f'oo")); + assertThat(escape("f'oo")).isEqualTo("\"f'oo\""); } @Test public void shouldConvertAStringWithAQuotIntoOneWithTicks() { - assertEquals("'f\"oo'", Quotes.escape("f\"oo")); + assertThat(escape("f\"oo")).isEqualTo("'f\"oo'"); } @Test public void shouldProvideConcatenatedStringsWhenStringToEscapeContainsTicksAndQuotes() { - assertEquals("concat(\"f\", '\"', \"o'o\")", Quotes.escape("f\"o'o")); + assertThat(escape("f\"o'o")).isEqualTo("concat(\"f\", '\"', \"o'o\")"); } /** @@ -51,7 +49,7 @@ public void shouldProvideConcatenatedStringsWhenStringToEscapeContainsTicksAndQu */ @Test public void shouldProvideConcatenatedStringsWhenStringEndsWithQuote() { - assertEquals("concat(\"Bar \", '\"', \"Rock'n'Roll\", '\"')", Quotes.escape( - "Bar \"Rock'n'Roll\"")); + assertThat(escape( + "Bar \"Rock'n'Roll\"")).isEqualTo("concat(\"Bar \", '\"', \"Rock'n'Roll\", '\"')"); } } diff --git a/java/client/test/org/openqa/selenium/support/ui/SelectElementTest.java b/java/client/test/org/openqa/selenium/support/ui/SelectElementTest.java index cc95860a9c789..02d3974a44a19 100644 --- a/java/client/test/org/openqa/selenium/support/ui/SelectElementTest.java +++ b/java/client/test/org/openqa/selenium/support/ui/SelectElementTest.java @@ -17,13 +17,11 @@ package org.openqa.selenium.support.ui; -import static org.hamcrest.CoreMatchers.instanceOf; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.openqa.selenium.testing.Driver.ALL; -import static org.openqa.selenium.testing.TestUtilities.catchThrowable; + +import com.google.common.collect.ImmutableList; import org.junit.Before; import org.junit.Test; @@ -33,8 +31,6 @@ import org.openqa.selenium.testing.Ignore; import org.openqa.selenium.testing.JUnit4TestBase; -import java.util.List; - public class SelectElementTest extends JUnit4TestBase { @Before @@ -45,64 +41,52 @@ public void runBeforeEveryTest() { @Test public void shouldThrowAnExceptionIfTheElementIsNotASelectElement() { WebElement selectElement = driver.findElement(By.name("checky")); - Throwable t = catchThrowable(() -> new Select(selectElement)); - assertThat(t, instanceOf(UnexpectedTagNameException.class)); + assertThatExceptionOfType(UnexpectedTagNameException.class) + .isThrownBy(() -> new Select(selectElement)); } @Test public void shouldIndicateThatASelectCanSupportMultipleOptions() { WebElement selectElement = driver.findElement(By.name("multi")); Select select = new Select(selectElement); - assertTrue(select.isMultiple()); + assertThat(select.isMultiple()).isTrue(); } @Test public void shouldIndicateThatASelectCanSupportMultipleOptionsWithEmptyMultipleAttribute() { WebElement selectElement = driver.findElement(By.name("select_empty_multiple")); Select select = new Select(selectElement); - assertTrue(select.isMultiple()); + assertThat(select.isMultiple()).isTrue(); } @Test public void shouldIndicateThatASelectCanSupportMultipleOptionsWithTrueMultipleAttribute() { WebElement selectElement = driver.findElement(By.name("multi_true")); Select select = new Select(selectElement); - assertTrue(select.isMultiple()); + assertThat(select.isMultiple()).isTrue(); } @Test public void shouldNotIndicateThatANormalSelectSupportsMulitpleOptions() { WebElement selectElement = driver.findElement(By.name("selectomatic")); Select select = new Select(selectElement); - assertFalse(select.isMultiple()); + assertThat(select.isMultiple()).isFalse(); } @Test public void shouldIndicateThatASelectCanSupportMultipleOptionsWithFalseMultipleAttribute() { WebElement selectElement = driver.findElement(By.name("multi_false")); Select select = new Select(selectElement); - assertTrue(select.isMultiple()); + assertThat(select.isMultiple()).isTrue(); } @Test public void shouldReturnAllOptionsWhenAsked() { WebElement selectElement = driver.findElement(By.name("selectomatic")); Select select = new Select(selectElement); - List returnedOptions = select.getOptions(); - - assertEquals(4,returnedOptions.size()); - - String one = returnedOptions.get(0).getText(); - assertEquals("One", one); - - String two = returnedOptions.get(1).getText(); - assertEquals("Two", two); - - String three = returnedOptions.get(2).getText(); - assertEquals("Four", three); - String four = returnedOptions.get(3).getText(); - assertEquals("Still learning how to count, apparently", four); + assertThat(select.getOptions()).extracting(WebElement::getText) + .isEqualTo(ImmutableList.of("One", "Two", "Four", "Still learning how to count, apparently")); } @@ -111,12 +95,8 @@ public void shouldReturnOptionWhichIsSelected() { WebElement selectElement = driver.findElement(By.name("selectomatic")); Select select = new Select(selectElement); - List returnedOptions = select.getAllSelectedOptions(); - - assertEquals(1,returnedOptions.size()); - - String one = returnedOptions.get(0).getText(); - assertEquals("One", one); + assertThat(select.getAllSelectedOptions()).extracting(WebElement::getText) + .isEqualTo(ImmutableList.of("One")); } @Test @@ -124,15 +104,8 @@ public void shouldReturnOptionsWhichAreSelected() { WebElement selectElement = driver.findElement(By.name("multi")); Select select = new Select(selectElement); - List returnedOptions = select.getAllSelectedOptions(); - - assertEquals(2,returnedOptions.size()); - - String one = returnedOptions.get(0).getText(); - assertEquals("Eggs", one); - - String two = returnedOptions.get(1).getText(); - assertEquals("Sausages", two); + assertThat(select.getAllSelectedOptions()).extracting(WebElement::getText) + .isEqualTo(ImmutableList.of("Eggs", "Sausages")); } @Test @@ -141,8 +114,7 @@ public void shouldReturnFirstSelectedOption() { Select select = new Select(selectElement); WebElement firstSelected = select.getFirstSelectedOption(); - - assertEquals("Eggs",firstSelected.getText()); + assertThat(firstSelected.getText()).isEqualTo("Eggs"); } @Test @@ -150,8 +122,8 @@ public void shouldThrowANoSuchElementExceptionIfNothingIsSelected() { WebElement selectElement = driver.findElement(By.name("select_empty_multiple")); Select select = new Select(selectElement); - Throwable t = catchThrowable(select::getFirstSelectedOption); - assertThat(t, instanceOf(NoSuchElementException.class)); + assertThatExceptionOfType(NoSuchElementException.class) + .isThrownBy(select::getFirstSelectedOption); } @Test @@ -160,7 +132,7 @@ public void shouldAllowOptionsToBeSelectedByVisibleText() { Select select = new Select(selectElement); select.selectByVisibleText("select_2"); WebElement firstSelected = select.getFirstSelectedOption(); - assertEquals("select_2",firstSelected.getText()); + assertThat(firstSelected.getText()).isEqualTo("select_2"); } @Test @@ -169,8 +141,8 @@ public void shouldNotAllowInvisibleOptionsToBeSelectedByVisibleText() { WebElement selectElement = driver.findElement(By.id("invisi_select")); Select select = new Select(selectElement); - Throwable t = catchThrowable(() -> select.selectByVisibleText("Apples")); - assertThat(t, instanceOf(NoSuchElementException.class)); + assertThatExceptionOfType(NoSuchElementException.class) + .isThrownBy(() -> select.selectByVisibleText("Apples")); } @Test @@ -178,8 +150,8 @@ public void shouldThrowExceptionOnSelectByVisibleTextIfOptionDoesNotExist() { WebElement selectElement = driver.findElement(By.name("select_empty_multiple")); Select select = new Select(selectElement); - Throwable t = catchThrowable(() -> select.selectByVisibleText("not there")); - assertThat(t, instanceOf(NoSuchElementException.class)); + assertThatExceptionOfType(NoSuchElementException.class) + .isThrownBy(() -> select.selectByVisibleText("not there")); } @Test @@ -188,7 +160,7 @@ public void shouldAllowOptionsToBeSelectedByIndex() { Select select = new Select(selectElement); select.selectByIndex(1); WebElement firstSelected = select.getFirstSelectedOption(); - assertEquals("select_2",firstSelected.getText()); + assertThat(firstSelected.getText()).isEqualTo("select_2"); } @Test @@ -196,8 +168,8 @@ public void shouldThrowExceptionOnSelectByIndexIfOptionDoesNotExist() { WebElement selectElement = driver.findElement(By.name("select_empty_multiple")); Select select = new Select(selectElement); - Throwable t = catchThrowable(() -> select.selectByIndex(10)); - assertThat(t, instanceOf(NoSuchElementException.class)); + assertThatExceptionOfType(NoSuchElementException.class) + .isThrownBy(() -> select.selectByIndex(10)); } @Test @@ -206,7 +178,7 @@ public void shouldAllowOptionsToBeSelectedByReturnedValue() { Select select = new Select(selectElement); select.selectByValue("select_2"); WebElement firstSelected = select.getFirstSelectedOption(); - assertEquals("select_2",firstSelected.getText()); + assertThat(firstSelected.getText()).isEqualTo("select_2"); } @Test @@ -214,8 +186,8 @@ public void shouldThrowExceptionOnSelectByReturnedValueIfOptionDoesNotExist() { WebElement selectElement = driver.findElement(By.name("select_empty_multiple")); Select select = new Select(selectElement); - Throwable t = catchThrowable(() -> select.selectByValue("not there")); - assertThat(t, instanceOf(NoSuchElementException.class)); + assertThatExceptionOfType(NoSuchElementException.class) + .isThrownBy(() -> select.selectByValue("not there")); } @Test @@ -223,9 +195,8 @@ public void shouldAllowUserToDeselectAllWhenSelectSupportsMultipleSelections() { WebElement selectElement = driver.findElement(By.name("multi")); Select select = new Select(selectElement); select.deselectAll(); - List returnedOptions = select.getAllSelectedOptions(); - assertEquals(0,returnedOptions.size()); + assertThat(select.getAllSelectedOptions()).isEmpty(); } @Test @@ -233,8 +204,7 @@ public void shouldNotAllowUserToDeselectAllWhenSelectDoesNotSupportMultipleSelec WebElement selectElement = driver.findElement(By.name("selectomatic")); Select select = new Select(selectElement); - Throwable t = catchThrowable(select::deselectAll); - assertThat(t, instanceOf(UnsupportedOperationException.class)); + assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(select::deselectAll); } @Test @@ -242,9 +212,8 @@ public void shouldAllowUserToDeselectOptionsByVisibleText() { WebElement selectElement = driver.findElement(By.name("multi")); Select select = new Select(selectElement); select.deselectByVisibleText("Eggs"); - List returnedOptions = select.getAllSelectedOptions(); - assertEquals(1,returnedOptions.size()); + assertThat(select.getAllSelectedOptions()).hasSize(1); } @Test @@ -253,8 +222,8 @@ public void shouldNotAllowUserToDeselectOptionsByInvisibleText() { WebElement selectElement = driver.findElement(By.id("invisi_select")); Select select = new Select(selectElement); - Throwable t = catchThrowable(() -> select.deselectByVisibleText("Apples")); - assertThat(t, instanceOf(NoSuchElementException.class)); + assertThatExceptionOfType(NoSuchElementException.class) + .isThrownBy(() -> select.deselectByVisibleText("Apples")); } @Test @@ -262,9 +231,8 @@ public void shouldAllowOptionsToBeDeselectedByIndex() { WebElement selectElement = driver.findElement(By.name("multi")); Select select = new Select(selectElement); select.deselectByIndex(0); - List returnedOptions = select.getAllSelectedOptions(); - assertEquals(1,returnedOptions.size()); + assertThat(select.getAllSelectedOptions()).hasSize(1); } @Test @@ -272,9 +240,8 @@ public void shouldAllowOptionsToBeDeselectedByReturnedValue() { WebElement selectElement = driver.findElement(By.name("multi")); Select select = new Select(selectElement); select.deselectByValue("eggs"); - List returnedOptions = select.getAllSelectedOptions(); - assertEquals(1,returnedOptions.size()); + assertThat(select.getAllSelectedOptions()).hasSize(1); } @Test @@ -283,9 +250,8 @@ public void shouldAllowOptionsToBeSelectedFromTheSelectElementThatIsNarrowerThan WebElement selectElement = driver.findElement(By.id("narrow")); Select select = new Select(selectElement); select.selectByIndex(1); - List returnedOptions = select.getAllSelectedOptions(); - assertEquals(1,returnedOptions.size()); + assertThat(select.getAllSelectedOptions()).hasSize(1); } @Test @@ -293,8 +259,8 @@ public void shouldThrowExceptionOnDeselectByReturnedValueIfOptionDoesNotExist() WebElement selectElement = driver.findElement(By.name("select_empty_multiple")); Select select = new Select(selectElement); - Throwable t = catchThrowable(() -> select.deselectByValue("not there")); - assertThat(t, instanceOf(NoSuchElementException.class)); + assertThatExceptionOfType(NoSuchElementException.class) + .isThrownBy(() -> select.deselectByValue("not there")); } @Test @@ -302,8 +268,8 @@ public void shouldThrowExceptionOnDeselectByVisibleTextIfOptionDoesNotExist() { WebElement selectElement = driver.findElement(By.name("select_empty_multiple")); Select select = new Select(selectElement); - Throwable t = catchThrowable(() -> select.deselectByVisibleText("not there")); - assertThat(t, instanceOf(NoSuchElementException.class)); + assertThatExceptionOfType(NoSuchElementException.class) + .isThrownBy(() -> select.deselectByVisibleText("not there")); } @Test @@ -311,8 +277,8 @@ public void shouldThrowExceptionOnDeselectByIndexIfOptionDoesNotExist() { WebElement selectElement = driver.findElement(By.name("select_empty_multiple")); Select select = new Select(selectElement); - Throwable t = catchThrowable(() -> select.deselectByIndex(10)); - assertThat(t, instanceOf(NoSuchElementException.class)); + assertThatExceptionOfType(NoSuchElementException.class) + .isThrownBy(() -> select.deselectByIndex(10)); } @Test @@ -320,8 +286,8 @@ public void shouldNotAllowUserToDeselectByIndexWhenSelectDoesNotSupportMultipleS WebElement selectElement = driver.findElement(By.name("selectomatic")); Select select = new Select(selectElement); - Throwable t = catchThrowable(() -> select.deselectByIndex(10)); - assertThat(t, instanceOf(UnsupportedOperationException.class)); + assertThatExceptionOfType(UnsupportedOperationException.class) + .isThrownBy(() -> select.deselectByIndex(10)); } @Test @@ -329,8 +295,8 @@ public void shouldNotAllowUserToDeselectByValueWhenSelectDoesNotSupportMultipleS WebElement selectElement = driver.findElement(By.name("selectomatic")); Select select = new Select(selectElement); - Throwable t = catchThrowable(() -> select.deselectByValue("two")); - assertThat(t, instanceOf(UnsupportedOperationException.class)); + assertThatExceptionOfType(UnsupportedOperationException.class) + .isThrownBy(() -> select.deselectByValue("two")); } @Test @@ -338,7 +304,7 @@ public void shouldNotAllowUserToDeselectByVisibleTextWhenSelectDoesNotSupportMul WebElement selectElement = driver.findElement(By.name("selectomatic")); Select select = new Select(selectElement); - Throwable t = catchThrowable(() -> select.deselectByVisibleText("Four")); - assertThat(t, instanceOf(UnsupportedOperationException.class)); + assertThatExceptionOfType(UnsupportedOperationException.class) + .isThrownBy(() -> select.deselectByVisibleText("Four")); } } diff --git a/java/client/test/org/openqa/selenium/support/ui/SelectLargeTest.java b/java/client/test/org/openqa/selenium/support/ui/SelectLargeTest.java index 3a4dcfe655079..1e9b90c5f12f9 100644 --- a/java/client/test/org/openqa/selenium/support/ui/SelectLargeTest.java +++ b/java/client/test/org/openqa/selenium/support/ui/SelectLargeTest.java @@ -17,7 +17,9 @@ package org.openqa.selenium.support.ui; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; + +import com.google.common.collect.ImmutableList; import org.junit.Test; import org.openqa.selenium.By; @@ -42,12 +44,11 @@ public void multipleSelectShouldBePossibleIfMulitpleAttributeEmpty() { selection.selectByIndex(2); List picked = selection.getAllSelectedOptions(); - assertEquals(2, picked.size()); - assertEquals("multi_2", picked.get(0).getAttribute("id")); - assertEquals("multi_3", picked.get(1).getAttribute("id")); + assertThat(picked).extracting(element -> element.getAttribute("id")) + .isEqualTo(ImmutableList.of("multi_2", "multi_3")); selection.deselectAll(); - assertEquals(0, selection.getAllSelectedOptions().size()); + assertThat(selection.getAllSelectedOptions()).isEmpty(); } @Test @@ -59,22 +60,22 @@ public void selectByVisibleTextShouldNormalizeSpaces() { String one = selection.getOptions().get(0).getText(); selection.selectByVisibleText(one); - assertEquals(one, selection.getFirstSelectedOption().getText()); + assertThat(selection.getFirstSelectedOption().getText()).isEqualTo(one); String two = selection.getOptions().get(1).getText(); selection.selectByVisibleText(two); - assertEquals(two, selection.getFirstSelectedOption().getText()); + assertThat(selection.getFirstSelectedOption().getText()).isEqualTo(two); String four = selection.getOptions().get(2).getText(); System.out.println("four = " + four); selection.selectByVisibleText(four.trim()); - assertEquals(four, selection.getFirstSelectedOption().getText()); + assertThat(selection.getFirstSelectedOption().getText()).isEqualTo(four); String longOptionText = selection.getOptions().get(3).getText(); System.out.println("longOptionText = " + longOptionText); selection.selectByVisibleText(longOptionText.trim()); - assertEquals(longOptionText, selection.getFirstSelectedOption().getText()); + assertThat(selection.getFirstSelectedOption().getText()).isEqualTo(longOptionText); } } diff --git a/java/client/test/org/openqa/selenium/support/ui/SelectTest.java b/java/client/test/org/openqa/selenium/support/ui/SelectTest.java index 31ec57da90214..4be8f71b23220 100644 --- a/java/client/test/org/openqa/selenium/support/ui/SelectTest.java +++ b/java/client/test/org/openqa/selenium/support/ui/SelectTest.java @@ -17,29 +17,23 @@ package org.openqa.selenium.support.ui; -import static java.util.Arrays.asList; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; import org.mockito.Mockito; import org.openqa.selenium.By; import org.openqa.selenium.NoSuchElementException; import org.openqa.selenium.WebElement; +import java.util.Arrays; import java.util.Collections; import java.util.List; -@RunWith(JUnit4.class) public class SelectTest{ @Test(expected = UnexpectedTagNameException.class) @@ -57,20 +51,19 @@ private Select selectElementWithMultipleEqualTo(final String multipleAttribute) @Test public void shouldIndicateThatASelectCanSupportMultipleOptions() { Select select = selectElementWithMultipleEqualTo("multiple"); - assertTrue(select.isMultiple()); + assertThat(select.isMultiple()).isTrue(); } @Test public void shouldIndicateThatASelectCanSupportMultipleOptionsWithEmptyMultipleAttribute() { Select select = selectElementWithMultipleEqualTo(""); - assertTrue(select.isMultiple()); + assertThat(select.isMultiple()).isTrue(); } @Test public void shouldNotIndicateThatANormalSelectSupportsMultipleOptions() { Select select = selectElementWithMultipleEqualTo(null); - - assertFalse(select.isMultiple()); + assertThat(select.isMultiple()).isFalse(); } private WebElement mockSelectWebElement(String multiple) { @@ -83,7 +76,6 @@ private WebElement mockSelectWebElement(String multiple) { private Select selectWithOptions(List options) { final WebElement element = mockSelectWebElement("multiple"); when(element.findElements(By.tagName("option"))).thenReturn(options); - return new Select(element); } @@ -92,7 +84,7 @@ public void shouldReturnAllOptionsWhenAsked() { final List expectedOptions = Collections.emptyList(); Select select = selectWithOptions(expectedOptions); - assertSame(expectedOptions, select.getOptions()); + assertThat(select.getOptions()).isSameAs(expectedOptions); } private WebElement mockOption(String name, boolean isSelected) { @@ -111,33 +103,34 @@ private WebElement mockOption(String name, boolean isSelected, int index) { public void shouldReturnOptionsWhichAreSelected() { final WebElement optionGood = mockOption("good", true); final WebElement optionBad = mockOption("bad", false); - final List options = asList(optionBad, optionGood); + final List options = Arrays.asList(optionBad, optionGood); Select select = selectWithOptions(options); List returnedOptions = select.getAllSelectedOptions(); - assertEquals(1, returnedOptions.size()); - assertSame(optionGood, returnedOptions.get(0)); + assertThat(returnedOptions).hasSize(1); + assertThat(returnedOptions.get(0)).isSameAs(optionGood); } @Test public void shouldReturnFirstSelectedOptions() { final WebElement firstOption = mockOption("first", true); final WebElement secondOption = mockOption("second", true); - final List options = asList(firstOption, secondOption); + final List options = Arrays.asList(firstOption, secondOption); Select select = selectWithOptions(options); WebElement firstSelected = select.getFirstSelectedOption(); - assertSame(firstOption, firstSelected); + assertThat(firstSelected).isSameAs(firstOption); } - @Test(expected = NoSuchElementException.class) + @Test public void shouldThrowANoSuchElementExceptionIfNothingIsSelected() { final WebElement firstOption = mockOption("first", false); - Select select = selectWithOptions(asList(firstOption)); + Select select = selectWithOptions(Collections.singletonList(firstOption)); - select.getFirstSelectedOption(); + assertThatExceptionOfType(NoSuchElementException.class) + .isThrownBy(select::getFirstSelectedOption); } @Test @@ -146,7 +139,7 @@ public void shouldAllowOptionsToBeSelectedByVisibleText() { final WebElement element = mockSelectWebElement("multiple"); when(element.findElements(By.xpath(".//option[normalize-space(.) = \"fish\"]"))) - .thenReturn(asList(firstOption)); + .thenReturn(Collections.singletonList(firstOption)); Select select = new Select(element); select.selectByVisibleText("fish"); @@ -159,7 +152,7 @@ public void shouldAllowOptionsToBeSelectedByIndex() { final WebElement firstOption = mockOption("first", true, 0); final WebElement secondOption = mockOption("second", false, 1); - Select select = selectWithOptions(asList(firstOption, secondOption)); + Select select = selectWithOptions(Arrays.asList(firstOption, secondOption)); select.selectByIndex(1); verify(firstOption, never()).click(); @@ -172,7 +165,7 @@ public void shouldAllowOptionsToBeSelectedByReturnedValue() { final WebElement element = mockSelectWebElement("multiple"); when(element.findElements(By.xpath(".//option[@value = \"b\"]"))).thenReturn( - asList(firstOption)); + Collections.singletonList(firstOption)); Select select = new Select(element); select.selectByValue("b"); @@ -185,7 +178,7 @@ public void shouldAllowUserToDeselectAllWhenSelectSupportsMultipleSelections() { final WebElement firstOption = mockOption("first", true); final WebElement secondOption = mockOption("second", false); - Select select = selectWithOptions(asList(firstOption, secondOption)); + Select select = selectWithOptions(Arrays.asList(firstOption, secondOption)); select.deselectAll(); verify(firstOption).click(); @@ -205,7 +198,7 @@ public void shouldAllowUserToDeselectOptionsByVisibleText() { final WebElement element = mockSelectWebElement("multiple"); when(element.findElements(By.xpath(".//option[normalize-space(.) = \"b\"]"))) - .thenReturn(asList(firstOption, secondOption)); + .thenReturn(Arrays.asList(firstOption, secondOption)); Select select = new Select(element); select.deselectByVisibleText("b"); @@ -219,7 +212,7 @@ public void shouldAllowOptionsToBeDeselectedByIndex() { final WebElement firstOption = mockOption("first", true, 2); final WebElement secondOption = mockOption("second", false, 1); - Select select = selectWithOptions(asList(firstOption, secondOption)); + Select select = selectWithOptions(Arrays.asList(firstOption, secondOption)); select.deselectByIndex(2); verify(firstOption).click(); @@ -233,7 +226,7 @@ public void shouldAllowOptionsToBeDeselectedByReturnedValue() { final WebElement element = mockSelectWebElement("multiple"); when(element.findElements(By.xpath(".//option[@value = \"b\"]"))) - .thenReturn(asList(firstOption, secondOption)); + .thenReturn(Arrays.asList(firstOption, secondOption)); Select select = new Select(element); select.deselectByValue("b"); @@ -251,7 +244,7 @@ public void shouldFallBackToSlowLooksUpsWhenGetByVisibleTextFailsAndThereIsASpac final WebElement element = mockSelectWebElement("multiple"); when(element.getTagName()).thenReturn("select"); when(element.getAttribute("multiple")).thenReturn("false"); - when(element.findElements(xpath1)).thenReturn(Collections.emptyList()); + when(element.findElements(xpath1)).thenReturn(Collections.emptyList()); when(element.findElements(xpath2)).thenReturn(Collections.singletonList(firstOption)); when(firstOption.getText()).thenReturn("foo bar"); @@ -263,35 +256,26 @@ public void shouldFallBackToSlowLooksUpsWhenGetByVisibleTextFailsAndThereIsASpac @Test public void shouldIndicateWhetherASelectIsMultipleCorrectly() { - assertFalse(selectElementWithMultipleEqualTo("false").isMultiple()); - assertFalse(selectElementWithMultipleEqualTo(null).isMultiple()); - assertTrue(selectElementWithMultipleEqualTo("true").isMultiple()); - assertTrue(selectElementWithMultipleEqualTo("multiple").isMultiple()); + assertThat(selectElementWithMultipleEqualTo("false").isMultiple()).isFalse(); + assertThat(selectElementWithMultipleEqualTo(null).isMultiple()).isFalse(); + assertThat(selectElementWithMultipleEqualTo("true").isMultiple()).isTrue(); + assertThat(selectElementWithMultipleEqualTo("multiple").isMultiple()).isTrue(); } @Test public void shouldThrowAnExceptionIfThereAreNoElementsToSelect() { final WebElement element = mockSelectWebElement("false"); - when(element.findElements(Mockito.any())).thenReturn(Collections.emptyList()); + when(element.findElements(Mockito.any())).thenReturn(Collections.emptyList()); Select select = new Select(element); - try { - select.selectByIndex(12); - fail("Was not meant to pass"); - } catch (NoSuchElementException ignored) { - } - - try { - select.selectByValue("not there"); - fail("Was not meant to pass"); - } catch (NoSuchElementException ignored) { - } - - try { - select.selectByVisibleText("also not there"); - fail("Was not meant to pass"); - } catch (NoSuchElementException ignored) { - } + assertThatExceptionOfType(NoSuchElementException.class) + .isThrownBy(() -> select.selectByIndex(12)); + + assertThatExceptionOfType(NoSuchElementException.class) + .isThrownBy(() -> select.selectByValue("not there")); + + assertThatExceptionOfType(NoSuchElementException.class) + .isThrownBy(() -> select.selectByVisibleText("also not there")); } } diff --git a/java/client/test/org/openqa/selenium/support/ui/SlowLoadableComponentTest.java b/java/client/test/org/openqa/selenium/support/ui/SlowLoadableComponentTest.java index cc1e3cac2cbf1..241211de3c83a 100644 --- a/java/client/test/org/openqa/selenium/support/ui/SlowLoadableComponentTest.java +++ b/java/client/test/org/openqa/selenium/support/ui/SlowLoadableComponentTest.java @@ -17,23 +17,16 @@ package org.openqa.selenium.support.ui; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; -@RunWith(JUnit4.class) public class SlowLoadableComponentTest { @Test public void testShouldDoNothingIfComponentIsAlreadyLoaded() { - try { - new DetonatingSlowLoader().get(); - } catch (RuntimeException e) { - fail("Did not expect load to be called"); - } + new DetonatingSlowLoader().get(); } @Test @@ -41,40 +34,24 @@ public void testShouldCauseTheLoadMethodToBeCalledIfTheComponentIsNotAlreadyLoad int numberOfTimesThroughLoop = 1; SlowLoading slowLoading = new SlowLoading(new SystemClock(), 1, numberOfTimesThroughLoop).get(); - assertEquals(numberOfTimesThroughLoop, slowLoading.getLoopCount()); + assertThat(slowLoading.getLoopCount()).isEqualTo(numberOfTimesThroughLoop); } @Test public void testTheLoadMethodShouldOnlyBeCalledOnceIfTheComponentTakesALongTimeToLoad() { - try { - new OnlyOneLoad(new SystemClock(), 5, 5).get(); - } catch (RuntimeException e) { - fail("Did not expect load to be called more than once"); - } + new OnlyOneLoad(new SystemClock(), 5, 5).get(); } @Test public void testShouldThrowAnErrorIfCallingLoadDoesNotCauseTheComponentToLoadBeforeTimeout() { FakeClock clock = new FakeClock(); - try { - new BasicSlowLoader(clock, 2).get(); - } catch (Error e) { - // We expect to time out - return; - } - fail(); + assertThatExceptionOfType(Error.class).isThrownBy(() -> new BasicSlowLoader(clock, 2).get()); } @Test public void testShouldCancelLoadingIfAnErrorIsDetected() { HasError error = new HasError(); - - try { - error.get(); - fail(); - } catch (CustomError e) { - // This is expected - } + assertThatExceptionOfType(CustomError.class).isThrownBy(error::get); } @@ -178,7 +155,7 @@ protected void load() { @Override protected void isLoaded() throws Error { - fail(); + throw new AssertionError(); } @Override diff --git a/java/client/test/org/openqa/selenium/support/ui/WebDriverWaitTest.java b/java/client/test/org/openqa/selenium/support/ui/WebDriverWaitTest.java index 80df410130443..d8ec4e6f6dbe5 100644 --- a/java/client/test/org/openqa/selenium/support/ui/WebDriverWaitTest.java +++ b/java/client/test/org/openqa/selenium/support/ui/WebDriverWaitTest.java @@ -17,16 +17,12 @@ package org.openqa.selenium.support.ui; -import static org.hamcrest.CoreMatchers.containsString; -import static org.hamcrest.CoreMatchers.instanceOf; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.mockito.Mockito.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.mockito.Mockito.withSettings; -import static org.openqa.selenium.testing.TestUtilities.catchThrowable; import org.junit.Before; import org.junit.Test; @@ -74,11 +70,10 @@ public void shouldIncludeRemoteInfoForWrappedDriverTimeout() throws IOException TickingClock clock = new TickingClock(); WebDriverWait wait = new WebDriverWait(testDriver, clock, clock, 1, 200); - Throwable ex = catchThrowable(() -> wait.until((d) -> false)); - assertNotNull(ex); - assertThat(ex, instanceOf(TimeoutException.class)); - assertThat(ex.getMessage(), containsString("Capabilities {javascriptEnabled: true, platform: ANY, platformName: ANY}")); - assertThat(ex.getMessage(), containsString("Session ID: foo")); + assertThatExceptionOfType(TimeoutException.class) + .isThrownBy(() -> wait.until((d) -> false)) + .withMessageContaining("Capabilities {javascriptEnabled: true, platform: ANY, platformName: ANY}") + .withMessageContaining("Session ID: foo"); } @Test @@ -86,9 +81,8 @@ public void shouldThrowAnExceptionIfTheTimerRunsOut() { TickingClock clock = new TickingClock(); WebDriverWait wait = new WebDriverWait(mockDriver, clock, clock, 1, 200); - Throwable ex = catchThrowable(() -> wait.until((d) -> false)); - assertNotNull(ex); - assertThat(ex, instanceOf(TimeoutException.class)); + assertThatExceptionOfType(TimeoutException.class) + .isThrownBy(() -> wait.until((d) -> false)); } @SuppressWarnings("unchecked") @@ -101,7 +95,7 @@ public void shouldSilentlyCaptureNoSuchElementExceptions() { TickingClock clock = new TickingClock(); Wait wait = new WebDriverWait(mockDriver, clock, clock, 5, 500); - assertSame(mockElement, wait.until(condition)); + assertThat(wait.until(condition)).isSameAs(mockElement); } @SuppressWarnings("unchecked") diff --git a/java/client/test/org/openqa/selenium/testing/BUCK b/java/client/test/org/openqa/selenium/testing/BUCK index d4c25ffc15840..55f8a02408394 100644 --- a/java/client/test/org/openqa/selenium/testing/BUCK +++ b/java/client/test/org/openqa/selenium/testing/BUCK @@ -55,7 +55,7 @@ java_library(name = 'test-base', '//java/client/src/org/openqa/selenium/support/ui:wait', '//java/client/test/org/openqa/selenium/testing/drivers:drivers', '//third_party/java/guava:guava', - '//third_party/java/hamcrest:hamcrest-library', + '//third_party/java/assertj:assertj', '//third_party/java/htmlunit:htmlunit', '//third_party/java/junit:junit', '//third_party/java/littleshoot:littleproxy', diff --git a/java/client/test/org/openqa/selenium/testing/JUnit4TestBase.java b/java/client/test/org/openqa/selenium/testing/JUnit4TestBase.java index e70fb37b86ba1..887c4370d989d 100644 --- a/java/client/test/org/openqa/selenium/testing/JUnit4TestBase.java +++ b/java/client/test/org/openqa/selenium/testing/JUnit4TestBase.java @@ -17,10 +17,7 @@ package org.openqa.selenium.testing; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.not; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import com.google.common.base.Throwables; @@ -75,7 +72,7 @@ public void prepareEnvironment() { String hostName = environment.getAppServer().getHostName(); String alternateHostName = environment.getAppServer().getAlternateHostName(); - assertThat(hostName, is(not(equalTo(alternateHostName)))); + assertThat(hostName).isNotEqualTo(alternateHostName); } @Rule diff --git a/java/server/.classpath b/java/server/.classpath index 36a0667ee80ad..d6fe8466b03da 100644 --- a/java/server/.classpath +++ b/java/server/.classpath @@ -8,8 +8,6 @@ - - diff --git a/java/server/server.iml b/java/server/server.iml index 369af3241f614..1338b2402e676 100644 --- a/java/server/server.iml +++ b/java/server/server.iml @@ -20,10 +20,10 @@ - + diff --git a/java/server/test/org/openqa/grid/e2e/BUCK b/java/server/test/org/openqa/grid/e2e/BUCK index 09580865b6323..d950648152915 100644 --- a/java/server/test/org/openqa/grid/e2e/BUCK +++ b/java/server/test/org/openqa/grid/e2e/BUCK @@ -23,7 +23,7 @@ java_library(name = 'tests', '//third_party/java/guava:guava', '//third_party/java/httpcomponents:httpclient', '//third_party/java/junit:junit', - '//third_party/java/hamcrest:hamcrest-library', + '//third_party/java/assertj:assertj', '//third_party/java/mockito:mockito-core', '//third_party/java/selenium:htmlunit-driver', '//third_party/java/servlet:javax.servlet-api', diff --git a/java/server/test/org/openqa/grid/e2e/misc/GridViaCommandLineTest.java b/java/server/test/org/openqa/grid/e2e/misc/GridViaCommandLineTest.java index 738b253fef1e6..ea607124dbf36 100644 --- a/java/server/test/org/openqa/grid/e2e/misc/GridViaCommandLineTest.java +++ b/java/server/test/org/openqa/grid/e2e/misc/GridViaCommandLineTest.java @@ -17,14 +17,8 @@ package org.openqa.grid.e2e.misc; -import static org.hamcrest.CoreMatchers.containsString; -import static org.hamcrest.CoreMatchers.instanceOf; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.CoreMatchers.startsWith; -import static org.hamcrest.Matchers.greaterThan; -import static org.hamcrest.Matchers.lessThan; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import com.google.common.base.Function; @@ -87,8 +81,8 @@ public void unrecognizedRole() { ByteArrayOutputStream outSpy = new ByteArrayOutputStream(); String[] args = {"-role", "hamlet"}; new GridLauncherV3(new PrintStream(outSpy), args).launch(); - assertThat(outSpy.toString(), - startsWith("Error: the role 'hamlet' does not match a recognized server role")); + assertThat(outSpy.toString()) + .startsWith("Error: the role 'hamlet' does not match a recognized server role"); } @Test @@ -96,7 +90,7 @@ public void canPrintVersion() { ByteArrayOutputStream outSpy = new ByteArrayOutputStream(); String[] args = {"-version"}; new GridLauncherV3(new PrintStream(outSpy), args).launch(); - assertThat(outSpy.toString(), startsWith("Selenium server version: ")); + assertThat(outSpy.toString()).startsWith("Selenium server version: "); } @Test @@ -104,8 +98,7 @@ public void canPrintGeneralHelp() { ByteArrayOutputStream outSpy = new ByteArrayOutputStream(); String[] args = {"-help"}; new GridLauncherV3(new PrintStream(outSpy), args).launch(); - assertThat(outSpy.toString(), startsWith("Usage:
[options]")); - assertThat(outSpy.toString(), containsString("-role")); + assertThat(outSpy.toString()).startsWith("Usage:
[options]").contains("-role"); } @Test @@ -113,8 +106,7 @@ public void canPrintHubHelp() { ByteArrayOutputStream outSpy = new ByteArrayOutputStream(); String[] args = {"-role", "hub", "-help"}; new GridLauncherV3(new PrintStream(outSpy), args).launch(); - assertThat(outSpy.toString(), startsWith("Usage:
[options]")); - assertThat(outSpy.toString(), containsString("-hubConfig")); + assertThat(outSpy.toString()).startsWith("Usage:
[options]").contains("-hubConfig"); } @Test @@ -122,8 +114,7 @@ public void canPrintNodeHelp() { ByteArrayOutputStream outSpy = new ByteArrayOutputStream(); String[] args = {"-role", "node", "-help"}; new GridLauncherV3(new PrintStream(outSpy), args).launch(); - assertThat(outSpy.toString(), startsWith("Usage:
[options]")); - assertThat(outSpy.toString(), containsString("-nodeConfig")); + assertThat(outSpy.toString()).startsWith("Usage:
[options]").contains("-nodeConfig"); } @Test @@ -137,7 +128,7 @@ public void canRedirectLogToFile() throws Exception { waitUntilServerIsAvailableOnPort(port); String log = String.join("", Files.readAllLines(tempLog)); - assertThat(log, containsString("Selenium Server is up and running on port " + port)); + assertThat(log).contains("Selenium Server is up and running on port " + port); } @Test @@ -148,15 +139,15 @@ public void canLaunchStandalone() throws Exception { server = new GridLauncherV3(new PrintStream(outSpy), args).launch(); assertTrue(server.isPresent()); - assertThat(server.get(), instanceOf(SeleniumServer.class)); + assertThat(server.get()).isInstanceOf(SeleniumServer.class); waitUntilServerIsAvailableOnPort(port); String content = getContentOf(port, "/"); - assertThat(content, containsString("Whoops! The URL specified routes to this help page.")); + assertThat(content).contains("Whoops! The URL specified routes to this help page."); String status = getContentOf(port, "/wd/hub/status"); Map statusMap = new Json().toType(status, Map.class); - assertThat(0L, is(statusMap.get("status"))); + assertThat(statusMap.get("status")).isEqualTo(0L); } @Test @@ -167,7 +158,7 @@ public void launchesStandaloneByDefault() throws Exception { server = new GridLauncherV3(new PrintStream(outSpy), args).launch(); assertTrue(server.isPresent()); - assertThat(server.get(), instanceOf(SeleniumServer.class)); + assertThat(server.get()).isInstanceOf(SeleniumServer.class); waitUntilServerIsAvailableOnPort(port); } @@ -183,7 +174,7 @@ public void canGetDebugLogFromStandalone() throws Exception { WebDriver driver = new RemoteWebDriver(new URL(String.format("http://localhost:%d/wd/hub", port)), DesiredCapabilities.htmlUnit()); driver.quit(); - assertThat(readAll(tempLog), containsString("DEBUG [WebDriverServlet.handle]")); + assertThat(readAll(tempLog)).contains("DEBUG [WebDriverServlet.handle]"); } @Test(timeout = 20000L) @@ -201,8 +192,7 @@ public void canSetSessionTimeoutForStandalone() throws Exception { new FluentWait<>(tempLog).withTimeout(Duration.ofSeconds(100)) .until(file -> readAll(file).contains("Removing session")); long end = System.currentTimeMillis(); - assertThat(end - start, greaterThan(5000L)); - assertThat(end - start, lessThan(15000L)); + assertThat(end - start).isBetween(5000L, 15000L); } private String readAll(Path file) { @@ -219,7 +209,7 @@ public void cannotStartHtmlSuite() { String[] args = {"-htmlSuite", "*quantum", "http://base.url", "suite.html", "report.html"}; new GridLauncherV3(new PrintStream(outSpy), args).launch(); - assertThat(outSpy.toString(), containsString("Download the Selenium HTML Runner")); + assertThat(outSpy.toString()).contains("Download the Selenium HTML Runner"); } @Test @@ -265,7 +255,7 @@ public void canStartHubUsingConfigFile() throws Exception { server = new GridLauncherV3(hubArgs).launch(); waitUntilServerIsAvailableOnPort(hubPort); - assertThat(server.get(), instanceOf(Hub.class)); + assertThat(server.get()).isInstanceOf(Hub.class); GridHubConfiguration realHubConfig = ((Hub) server.get()).getConfiguration(); assertEquals(10000, realHubConfig.cleanUpCycle.intValue()); assertEquals(30000, realHubConfig.browserTimeout.intValue()); diff --git a/java/server/test/org/openqa/grid/web/servlet/DisplayHelpServletTest.java b/java/server/test/org/openqa/grid/web/servlet/DisplayHelpServletTest.java index 378d16a8f9e1e..3d7f67e496de7 100644 --- a/java/server/test/org/openqa/grid/web/servlet/DisplayHelpServletTest.java +++ b/java/server/test/org/openqa/grid/web/servlet/DisplayHelpServletTest.java @@ -17,11 +17,7 @@ package org.openqa.grid.web.servlet; -import static org.hamcrest.CoreMatchers.containsString; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import org.junit.Before; import org.junit.Test; @@ -53,37 +49,38 @@ public ServletContext getServletContext() { @Test public void testGetHelpPageForStandalone() throws IOException, ServletException { - assertEquals(servlet.getInitParameter(DisplayHelpServlet.HELPER_TYPE_PARAMETER), "standalone"); - assertEquals(servlet.getInitParameter(ConsoleServlet.CONSOLE_PATH_PARAMETER), "/wd/hub"); + assertThat("standalone") + .isEqualTo(servlet.getInitParameter(DisplayHelpServlet.HELPER_TYPE_PARAMETER)); + assertThat("/wd/hub") + .isEqualTo(servlet.getInitParameter(ConsoleServlet.CONSOLE_PATH_PARAMETER)); FakeHttpServletResponse response = sendCommand("GET", "/"); - assertEquals(HttpServletResponse.SC_OK, response.getStatus()); + assertThat(response.getStatus()).isEqualTo(HttpServletResponse.SC_OK); String body = response.getBody(); - assertNotNull(body); - assertThat(body, containsString("Whoops! The URL specified routes to this help page.")); - assertThat(body, containsString("\"type\": \"Standalone\"")); - assertThat(body, containsString("\"consoleLink\": \"\\u002fwd\\u002fhub\"")); + assertThat(body).isNotNull().contains( + "Whoops! The URL specified routes to this help page.", + "\"type\": \"Standalone\"", + "\"consoleLink\": \"\\u002fwd\\u002fhub\""); } @Test public void testGetHelpPageAsset() throws IOException, ServletException { FakeHttpServletResponse response = sendCommand("GET", "/assets/displayhelpservlet.css"); - assertEquals(HttpServletResponse.SC_OK, response.getStatus()); - assertNotNull(response.getBody()); - assertTrue(response.getBody().contains("#help-heading #logo")); + assertThat(response.getStatus()).isEqualTo(HttpServletResponse.SC_OK); + assertThat(response.getBody()).isNotNull().contains("#help-heading #logo"); } @Test public void testNoSuchAsset() throws IOException, ServletException { FakeHttpServletResponse response = sendCommand("GET", "/assets/foo.bar"); - assertEquals(HttpServletResponse.SC_NOT_FOUND, response.getStatus()); + assertThat(response.getStatus()).isEqualTo(HttpServletResponse.SC_NOT_FOUND); } @Test public void testAccessRoot() throws IOException, ServletException { FakeHttpServletResponse response = sendCommand("GET", "/"); - assertEquals(HttpServletResponse.SC_OK, response.getStatus()); + assertThat(response.getStatus()).isEqualTo(HttpServletResponse.SC_OK); } } diff --git a/java/server/test/org/openqa/selenium/remote/server/BUCK b/java/server/test/org/openqa/selenium/remote/server/BUCK index 273853a43d576..cec4c9f29de8d 100644 --- a/java/server/test/org/openqa/selenium/remote/server/BUCK +++ b/java/server/test/org/openqa/selenium/remote/server/BUCK @@ -36,7 +36,7 @@ java_library(name = 'tests', '//java/server/test/org/openqa/testing:test-base', '//third_party/java/gson:gson', '//third_party/java/guava:guava', - '//third_party/java/hamcrest:hamcrest-library', + '//third_party/java/assertj:assertj', '//third_party/java/httpcomponents:httpclient', '//third_party/java/jetty:jetty', '//third_party/java/junit:junit', diff --git a/java/server/test/org/openqa/selenium/remote/server/CapabilitiesComparatorTest.java b/java/server/test/org/openqa/selenium/remote/server/CapabilitiesComparatorTest.java index 7b5b503ead910..7a77877e6a4ea 100644 --- a/java/server/test/org/openqa/selenium/remote/server/CapabilitiesComparatorTest.java +++ b/java/server/test/org/openqa/selenium/remote/server/CapabilitiesComparatorTest.java @@ -18,11 +18,7 @@ package org.openqa.selenium.remote.server; import static java.util.Collections.singletonList; -import static org.hamcrest.Matchers.anyOf; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.greaterThan; -import static org.hamcrest.Matchers.lessThan; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.openqa.selenium.remote.server.CapabilitiesComparator.getBestMatch; import static java.util.Arrays.asList; @@ -121,13 +117,13 @@ public void shouldPickCorrectBrowser() { DesiredCapabilities desired = new DesiredCapabilities(); desired.setBrowserName(BrowserType.CHROME); - assertThat(getBestMatch(desired, list), equalTo(chrome)); + assertThat(getBestMatch(desired, list)).isEqualTo(chrome); desired.setBrowserName(BrowserType.FIREFOX); - assertThat(getBestMatch(desired, list), equalTo(firefox)); + assertThat(getBestMatch(desired, list)).isEqualTo(firefox); desired.setBrowserName(BrowserType.OPERA); - assertThat(getBestMatch(desired, list), equalTo(opera)); + assertThat(getBestMatch(desired, list)).isEqualTo(opera); } @Test @@ -136,16 +132,16 @@ public void shouldPickAnyIfPlatformChoicesAreAnyOrWindowsAndDesireLinux() { Capabilities windows = capabilities(BrowserType.FIREFOX, "", Platform.WINDOWS, true); Capabilities linux = capabilities(BrowserType.FIREFOX, "", Platform.LINUX, true); - assertThat(getBestMatch(linux, asList(any, windows)), equalTo(any)); + assertThat(getBestMatch(linux, asList(any, windows))).isEqualTo(any); // Registration order should not matter. - assertThat(getBestMatch(linux, asList(windows, any)), equalTo(any)); + assertThat(getBestMatch(linux, asList(windows, any))).isEqualTo(any); } @Test public void shouldPickWindowsIfPlatformChoiceIsAny() { Capabilities any = capabilities(BrowserType.IE, "", Platform.ANY, true); Capabilities windows = capabilities(BrowserType.IE, "", Platform.WINDOWS, true); - assertThat(getBestMatch(any, singletonList(windows)), equalTo(windows)); + assertThat(getBestMatch(any, singletonList(windows))).isEqualTo(windows); } @Test @@ -156,10 +152,10 @@ public void shouldPickMostSpecificOperatingSystem() { Capabilities vista = capabilities(BrowserType.IE, "", Platform.VISTA, true); List list = asList(any, windows, xp, vista); - assertThat(getBestMatch(any, list), equalTo(any)); - assertThat(getBestMatch(windows, list), equalTo(windows)); - assertThat(getBestMatch(xp, list), equalTo(xp)); - assertThat(getBestMatch(vista, list), equalTo(vista)); + assertThat(getBestMatch(any, list)).isEqualTo(any); + assertThat(getBestMatch(windows, list)).isEqualTo(windows); + assertThat(getBestMatch(xp, list)).isEqualTo(xp); + assertThat(getBestMatch(vista, list)).isEqualTo(vista); } @Test @@ -169,13 +165,12 @@ public void pickingWindowsFromVariousLists() { Capabilities xp = capabilities(BrowserType.IE, "", Platform.XP, true); Capabilities vista = capabilities(BrowserType.IE, "", Platform.VISTA, true); - assertThat(getBestMatch(windows, singletonList(any)), equalTo(any)); - assertThat(getBestMatch(windows, asList(any, windows)), equalTo(windows)); - assertThat(getBestMatch(windows, asList(windows, xp, vista)), equalTo(windows)); - assertThat(getBestMatch(windows, asList(xp, vista)), - anyOf(equalTo(xp), equalTo(vista))); - assertThat(getBestMatch(windows, singletonList(xp)), equalTo(xp)); - assertThat(getBestMatch(windows, singletonList(vista)), equalTo(vista)); + assertThat(getBestMatch(windows, singletonList(any))).isEqualTo(any); + assertThat(getBestMatch(windows, asList(any, windows))).isEqualTo(windows); + assertThat(getBestMatch(windows, asList(windows, xp, vista))).isEqualTo(windows); + assertThat(getBestMatch(windows, asList(xp, vista))).isIn(xp, vista); + assertThat(getBestMatch(windows, singletonList(xp))).isEqualTo(xp); + assertThat(getBestMatch(windows, singletonList(vista))).isEqualTo(vista); } @Test @@ -185,13 +180,13 @@ public void pickingXpFromVariousLists() { Capabilities xp = capabilities(BrowserType.IE, "", Platform.XP, true); Capabilities vista = capabilities(BrowserType.IE, "", Platform.VISTA, true); - assertThat(getBestMatch(xp, singletonList(any)), equalTo(any)); - assertThat(getBestMatch(xp, asList(any, windows)), equalTo(windows)); - assertThat(getBestMatch(xp, asList(windows, xp, vista)), equalTo(xp)); - assertThat(getBestMatch(xp, asList(windows, xp)), equalTo(xp)); - assertThat(getBestMatch(xp, asList(xp, vista)), equalTo(xp)); - assertThat(getBestMatch(xp, singletonList(xp)), equalTo(xp)); - assertThat(getBestMatch(xp, singletonList(vista)), equalTo(vista)); + assertThat(getBestMatch(xp, singletonList(any))).isEqualTo(any); + assertThat(getBestMatch(xp, asList(any, windows))).isEqualTo(windows); + assertThat(getBestMatch(xp, asList(windows, xp, vista))).isEqualTo(xp); + assertThat(getBestMatch(xp, asList(windows, xp))).isEqualTo(xp); + assertThat(getBestMatch(xp, asList(xp, vista))).isEqualTo(xp); + assertThat(getBestMatch(xp, singletonList(xp))).isEqualTo(xp); + assertThat(getBestMatch(xp, singletonList(vista))).isEqualTo(vista); } @Test @@ -202,33 +197,33 @@ public void pickingVistaFromVariousLists() { Capabilities vista = capabilities(BrowserType.IE, "", Platform.VISTA, true); Platform current = Platform.WINDOWS; - assertThat(getBestMatch(vista, singletonList(any), current), equalTo(any)); - assertThat(getBestMatch(vista, asList(any, windows), current), equalTo(windows)); - assertThat(getBestMatch(vista, asList(windows, xp, vista), current), equalTo(vista)); - assertThat(getBestMatch(vista, asList(windows, xp), current), equalTo(windows)); - assertThat(getBestMatch(vista, asList(xp, vista), current), equalTo(vista)); - assertThat(getBestMatch(vista, singletonList(xp), current), equalTo(xp)); - assertThat(getBestMatch(vista, singletonList(vista), current), equalTo(vista)); + assertThat(getBestMatch(vista, singletonList(any), current)).isEqualTo(any); + assertThat(getBestMatch(vista, asList(any, windows), current)).isEqualTo(windows); + assertThat(getBestMatch(vista, asList(windows, xp, vista), current)).isEqualTo(vista); + assertThat(getBestMatch(vista, asList(windows, xp), current)).isEqualTo(windows); + assertThat(getBestMatch(vista, asList(xp, vista), current)).isEqualTo(vista); + assertThat(getBestMatch(vista, singletonList(xp), current)).isEqualTo(xp); + assertThat(getBestMatch(vista, singletonList(vista), current)).isEqualTo(vista); current = Platform.VISTA; - assertThat(getBestMatch(vista, singletonList(any), current), equalTo(any)); - assertThat(getBestMatch(vista, asList(any, windows), current), equalTo(windows)); - assertThat(getBestMatch(vista, asList(any, vista), current), equalTo(vista)); - assertThat(getBestMatch(vista, asList(windows, xp, vista), current), equalTo(vista)); - assertThat(getBestMatch(vista, asList(windows, xp), current), equalTo(windows)); - assertThat(getBestMatch(vista, asList(xp, vista), current), equalTo(vista)); - assertThat(getBestMatch(vista, singletonList(xp), current), equalTo(xp)); - assertThat(getBestMatch(vista, singletonList(vista), current), equalTo(vista)); + assertThat(getBestMatch(vista, singletonList(any), current)).isEqualTo(any); + assertThat(getBestMatch(vista, asList(any, windows), current)).isEqualTo(windows); + assertThat(getBestMatch(vista, asList(any, vista), current)).isEqualTo(vista); + assertThat(getBestMatch(vista, asList(windows, xp, vista), current)).isEqualTo(vista); + assertThat(getBestMatch(vista, asList(windows, xp), current)).isEqualTo(windows); + assertThat(getBestMatch(vista, asList(xp, vista), current)).isEqualTo(vista); + assertThat(getBestMatch(vista, singletonList(xp), current)).isEqualTo(xp); + assertThat(getBestMatch(vista, singletonList(vista), current)).isEqualTo(vista); current = Platform.XP; - assertThat(getBestMatch(vista, singletonList(any), current), equalTo(any)); - assertThat(getBestMatch(vista, asList(any, windows), current), equalTo(windows)); - assertThat(getBestMatch(vista, asList(any, vista), current), equalTo(vista)); - assertThat(getBestMatch(vista, asList(windows, xp, vista), current), equalTo(vista)); - assertThat(getBestMatch(vista, asList(windows, xp), current), equalTo(windows)); - assertThat(getBestMatch(vista, asList(xp, vista), current), equalTo(vista)); - assertThat(getBestMatch(vista, singletonList(xp), current), equalTo(xp)); - assertThat(getBestMatch(vista, singletonList(vista), current), equalTo(vista)); + assertThat(getBestMatch(vista, singletonList(any), current)).isEqualTo(any); + assertThat(getBestMatch(vista, asList(any, windows), current)).isEqualTo(windows); + assertThat(getBestMatch(vista, asList(any, vista), current)).isEqualTo(vista); + assertThat(getBestMatch(vista, asList(windows, xp, vista), current)).isEqualTo(vista); + assertThat(getBestMatch(vista, asList(windows, xp), current)).isEqualTo(windows); + assertThat(getBestMatch(vista, asList(xp, vista), current)).isEqualTo(vista); + assertThat(getBestMatch(vista, singletonList(xp), current)).isEqualTo(xp); + assertThat(getBestMatch(vista, singletonList(vista), current)).isEqualTo(vista); } @Test @@ -238,12 +233,12 @@ public void pickingUnixFromVariousLists() { Capabilities unix = capabilities(BrowserType.FIREFOX, "", Platform.UNIX, true); Capabilities linux = capabilities(BrowserType.FIREFOX, "", Platform.LINUX, true); - assertThat(getBestMatch(unix, singletonList(any)), equalTo(any)); - assertThat(getBestMatch(unix, asList(any, mac)), equalTo(any)); - assertThat(getBestMatch(unix, asList(any, unix)), equalTo(unix)); - assertThat(getBestMatch(unix, asList(any, unix, linux)), equalTo(unix)); - assertThat(getBestMatch(unix, asList(unix, linux)), equalTo(unix)); - assertThat(getBestMatch(unix, singletonList(linux)), equalTo(linux)); + assertThat(getBestMatch(unix, singletonList(any))).isEqualTo(any); + assertThat(getBestMatch(unix, asList(any, mac))).isEqualTo(any); + assertThat(getBestMatch(unix, asList(any, unix))).isEqualTo(unix); + assertThat(getBestMatch(unix, asList(any, unix, linux))).isEqualTo(unix); + assertThat(getBestMatch(unix, asList(unix, linux))).isEqualTo(unix); + assertThat(getBestMatch(unix, singletonList(linux))).isEqualTo(linux); } @Test @@ -253,13 +248,13 @@ public void pickingLinuxFromVariousLists() { Capabilities unix = capabilities(BrowserType.FIREFOX, "", Platform.UNIX, true); Capabilities linux = capabilities(BrowserType.FIREFOX, "", Platform.LINUX, true); - assertThat(getBestMatch(linux, singletonList(any)), equalTo(any)); - assertThat(getBestMatch(linux, asList(any, mac)), equalTo(any)); - assertThat(getBestMatch(linux, asList(any, unix)), equalTo(unix)); - assertThat(getBestMatch(linux, asList(any, unix, linux)), equalTo(linux)); - assertThat(getBestMatch(linux, asList(unix, linux)), equalTo(linux)); - assertThat(getBestMatch(linux, singletonList(linux)), equalTo(linux)); - assertThat(getBestMatch(linux, singletonList(unix)), equalTo(unix)); + assertThat(getBestMatch(linux, singletonList(any))).isEqualTo(any); + assertThat(getBestMatch(linux, asList(any, mac))).isEqualTo(any); + assertThat(getBestMatch(linux, asList(any, unix))).isEqualTo(unix); + assertThat(getBestMatch(linux, asList(any, unix, linux))).isEqualTo(linux); + assertThat(getBestMatch(linux, asList(unix, linux))).isEqualTo(linux); + assertThat(getBestMatch(linux, singletonList(linux))).isEqualTo(linux); + assertThat(getBestMatch(linux, singletonList(unix))).isEqualTo(unix); } @Test @@ -270,10 +265,10 @@ public void matchesByCapabilitiesProvided() { Capabilities windows = capabilities(BrowserType.IE, "", Platform.WINDOWS, true); Capabilities firefox = capabilities(BrowserType.FIREFOX, "", Platform.WINDOWS, true); - assertThat(getBestMatch(sparse, asList(windows, firefox)), equalTo(firefox)); + assertThat(getBestMatch(sparse, asList(windows, firefox))).isEqualTo(firefox); sparse.setBrowserName(BrowserType.IE); - assertThat(getBestMatch(sparse, asList(windows, firefox)), equalTo(windows)); + assertThat(getBestMatch(sparse, asList(windows, firefox))).isEqualTo(windows); } @Test @@ -287,21 +282,21 @@ public void matchesWithPreferenceToCurrentPlatform() { DesiredCapabilities.firefox()); // Should match to corresponding platform. - assertThat(getBestMatch(anyChrome, allCaps, Platform.UNIX), equalTo(chromeUnix)); - assertThat(getBestMatch(chromeUnix, allCaps, Platform.UNIX), equalTo(chromeUnix)); + assertThat(getBestMatch(anyChrome, allCaps, Platform.UNIX)).isEqualTo(chromeUnix); + assertThat(getBestMatch(chromeUnix, allCaps, Platform.UNIX)).isEqualTo(chromeUnix); - assertThat(getBestMatch(anyChrome, allCaps, Platform.LINUX), equalTo(chromeUnix)); - assertThat(getBestMatch(chromeUnix, allCaps, Platform.LINUX), equalTo(chromeUnix)); + assertThat(getBestMatch(anyChrome, allCaps, Platform.LINUX)).isEqualTo(chromeUnix); + assertThat(getBestMatch(chromeUnix, allCaps, Platform.LINUX)).isEqualTo(chromeUnix); - assertThat(getBestMatch(anyChrome, allCaps, Platform.VISTA), equalTo(chromeVista)); - assertThat(getBestMatch(chromeVista, allCaps, Platform.VISTA), equalTo(chromeVista)); + assertThat(getBestMatch(anyChrome, allCaps, Platform.VISTA)).isEqualTo(chromeVista); + assertThat(getBestMatch(chromeVista, allCaps, Platform.VISTA)).isEqualTo(chromeVista); - assertThat(getBestMatch(anyChrome, allCaps, Platform.WINDOWS), equalTo(chromeVista)); - assertThat(getBestMatch(chromeVista, allCaps, Platform.WINDOWS), equalTo(chromeVista)); + assertThat(getBestMatch(anyChrome, allCaps, Platform.WINDOWS)).isEqualTo(chromeVista); + assertThat(getBestMatch(chromeVista, allCaps, Platform.WINDOWS)).isEqualTo(chromeVista); // No configs registered to current platform, should fallback to normal matching rules. - assertThat(getBestMatch(anyChrome, allCaps, Platform.MAC), equalTo(anyChrome)); - assertThat(getBestMatch(anyChrome, allCaps, Platform.XP), equalTo(anyChrome)); + assertThat(getBestMatch(anyChrome, allCaps, Platform.MAC)).isEqualTo(anyChrome); + assertThat(getBestMatch(anyChrome, allCaps, Platform.XP)).isEqualTo(anyChrome); } @Test @@ -312,13 +307,13 @@ public void currentPlatformCheckDoesNotTrumpExactPlatformMatch() { List allCaps = asList(anyChrome, chromeVista, chromeUnix); - assertThat(getBestMatch(chromeVista, allCaps, Platform.UNIX), equalTo(chromeVista)); - assertThat(getBestMatch(chromeVista, allCaps, Platform.LINUX), equalTo(chromeVista)); - assertThat(getBestMatch(chromeVista, allCaps, Platform.MAC), equalTo(chromeVista)); + assertThat(getBestMatch(chromeVista, allCaps, Platform.UNIX)).isEqualTo(chromeVista); + assertThat(getBestMatch(chromeVista, allCaps, Platform.LINUX)).isEqualTo(chromeVista); + assertThat(getBestMatch(chromeVista, allCaps, Platform.MAC)).isEqualTo(chromeVista); - assertThat(getBestMatch(chromeUnix, allCaps, Platform.MAC), equalTo(chromeUnix)); - assertThat(getBestMatch(chromeUnix, allCaps, Platform.VISTA), equalTo(chromeUnix)); - assertThat(getBestMatch(chromeUnix, allCaps, Platform.WINDOWS), equalTo(chromeUnix)); + assertThat(getBestMatch(chromeUnix, allCaps, Platform.MAC)).isEqualTo(chromeUnix); + assertThat(getBestMatch(chromeUnix, allCaps, Platform.VISTA)).isEqualTo(chromeUnix); + assertThat(getBestMatch(chromeUnix, allCaps, Platform.WINDOWS)).isEqualTo(chromeUnix); } @Test @@ -330,8 +325,8 @@ public void currentPlatformCheckDoesNotTrumpExactVersionMatch() { List allCaps = asList(anyChrome, chromeVista, chromeUnix, chromeBetaUnix); - assertThat(getBestMatch(chromeUnix, allCaps, Platform.UNIX), equalTo(chromeUnix)); - assertThat(getBestMatch(chromeBetaUnix, allCaps, Platform.UNIX), equalTo(chromeBetaUnix)); + assertThat(getBestMatch(chromeUnix, allCaps, Platform.UNIX)).isEqualTo(chromeUnix); + assertThat(getBestMatch(chromeBetaUnix, allCaps, Platform.UNIX)).isEqualTo(chromeBetaUnix); } @Test @@ -343,8 +338,8 @@ public void absentExactMatchPrefersItemsInInputOrder() { List allCaps = asList(chromeWindows, chromeVista); List reversedCaps = Lists.reverse(allCaps); - assertThat(getBestMatch(anyChrome, allCaps, Platform.UNIX), equalTo(chromeWindows)); - assertThat(getBestMatch(anyChrome, reversedCaps, Platform.UNIX), equalTo(chromeVista)); + assertThat(getBestMatch(anyChrome, allCaps, Platform.UNIX)).isEqualTo(chromeWindows); + assertThat(getBestMatch(anyChrome, reversedCaps, Platform.UNIX)).isEqualTo(chromeVista); } @Test @@ -355,9 +350,9 @@ public void filtersByVersionStringIfNonEmpty() { List allCaps = asList(anyChrome, chromeBeta, chromeDev); - assertThat(getBestMatch(anyChrome, allCaps), equalTo(anyChrome)); - assertThat(getBestMatch(chromeBeta, allCaps), equalTo(chromeBeta)); - assertThat(getBestMatch(chromeDev, allCaps), equalTo(chromeDev)); + assertThat(getBestMatch(anyChrome, allCaps)).isEqualTo(anyChrome); + assertThat(getBestMatch(chromeBeta, allCaps)).isEqualTo(chromeBeta); + assertThat(getBestMatch(chromeDev, allCaps)).isEqualTo(chromeDev); } @Test @@ -373,15 +368,15 @@ public void ignoresVersionStringIfEmpty() { List allCaps = asList(anyChrome, chromeNoVersion); - assertThat(getBestMatch(chromeEmptyVersion, allCaps, Platform.UNIX), equalTo(chromeNoVersion)); - assertThat(getBestMatch(chromeNoVersion, allCaps, Platform.UNIX), equalTo(chromeNoVersion)); + assertThat(getBestMatch(chromeEmptyVersion, allCaps, Platform.UNIX)).isEqualTo(chromeNoVersion); + assertThat(getBestMatch(chromeNoVersion, allCaps, Platform.UNIX)).isEqualTo(chromeNoVersion); // Unix does not match windows. - assertThat(getBestMatch(anyChrome, allCaps, Platform.WINDOWS), equalTo(anyChrome)); + assertThat(getBestMatch(anyChrome, allCaps, Platform.WINDOWS)).isEqualTo(anyChrome); } private void assertGreaterThan(Capabilities a, Capabilities b) { - assertThat(comparator.compare(a, b), greaterThan(0)); - assertThat(comparator.compare(b, a), lessThan(0)); + assertThat(comparator.compare(a, b)).isGreaterThan(0); + assertThat(comparator.compare(b, a)).isLessThan(0); } private static Comparator compareBy(Capabilities capabilities) { diff --git a/java/server/test/org/openqa/selenium/remote/server/handler/StatusTest.java b/java/server/test/org/openqa/selenium/remote/server/handler/StatusTest.java index 70c82fcef2765..88e1e369b6be6 100644 --- a/java/server/test/org/openqa/selenium/remote/server/handler/StatusTest.java +++ b/java/server/test/org/openqa/selenium/remote/server/handler/StatusTest.java @@ -17,10 +17,7 @@ package org.openqa.selenium.remote.server.handler; -import static org.hamcrest.CoreMatchers.instanceOf; -import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; @@ -32,13 +29,14 @@ public class StatusTest { public void testStatusHandler() { Status status = new Status(); Object value = status.handle().getValue(); - assertThat(value, instanceOf(Map.class)); + assertThat(value).isInstanceOf(Map.class); Map valueMap = (Map) value; - assertThat(valueMap.get("ready"), is(true)); - assertThat(valueMap.get("message"), is("Server is running")); - assertTrue(valueMap.containsKey("build")); - assertTrue(valueMap.containsKey("os")); - assertTrue(valueMap.containsKey("java")); + assertThat(valueMap) + .containsEntry("ready", true) + .containsEntry("message", "Server is running") + .containsKey("build") + .containsKey("os") + .containsKey("java"); } } diff --git a/java/server/test/org/openqa/selenium/remote/server/rest/ResultConfigTest.java b/java/server/test/org/openqa/selenium/remote/server/rest/ResultConfigTest.java index 9bae5d0bdab28..bdbaa1aa942d6 100644 --- a/java/server/test/org/openqa/selenium/remote/server/rest/ResultConfigTest.java +++ b/java/server/test/org/openqa/selenium/remote/server/rest/ResultConfigTest.java @@ -17,17 +17,14 @@ package org.openqa.selenium.remote.server.rest; -import static org.hamcrest.Matchers.is; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.fail; import com.google.common.collect.ImmutableMap; import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; import org.openqa.selenium.NoSuchElementException; import org.openqa.selenium.WebDriverException; import org.openqa.selenium.remote.Command; @@ -39,29 +36,20 @@ import java.util.concurrent.ExecutionException; import java.util.logging.Logger; -@RunWith(JUnit4.class) public class ResultConfigTest { private Logger logger = Logger.getLogger(ResultConfigTest.class.getName()); private static final SessionId dummySessionId = new SessionId("Test"); @Test public void testShouldNotAllowNullToBeUsedAsTheUrl() { - try { - new ResultConfig(null, StubHandler.class, null, logger); - fail("Should have failed"); - } catch (IllegalArgumentException e) { - exceptionWasExpected(); - } + assertThatExceptionOfType(IllegalArgumentException.class) + .isThrownBy(() -> new ResultConfig(null, StubHandler.class, null, logger)); } @Test public void testShouldNotAllowNullToBeUsedForTheHandler() { - try { - new ResultConfig("/cheese", null, null, logger); - fail("Should have failed"); - } catch (IllegalArgumentException e) { - exceptionWasExpected(); - } + assertThatExceptionOfType(IllegalArgumentException.class) + .isThrownBy(() -> new ResultConfig("/cheese", null, null, logger)); } @Test @@ -72,7 +60,7 @@ public void testShouldSetNamedParametersOnHandler() { NamedParameterHandler handler = new NamedParameterHandler(); config.populate(handler, command); - assertThat(handler.getBar(), is("fishy")); + assertThat(handler.getBar()).isEqualTo("fishy"); } @SuppressWarnings({"ThrowableResultOfMethodCallIgnored"}) @@ -114,9 +102,6 @@ public void testDoesNotPeelTooManyLayersFromNestedExceptions() { assertEquals(noElement, toClient); } - private void exceptionWasExpected() { - } - public static class NamedParameterHandler implements RestishHandler { private String bar; diff --git a/third_party/java/assertj/BUCK b/third_party/java/assertj/BUCK new file mode 100644 index 0000000000000..764d490f5c6ea --- /dev/null +++ b/third_party/java/assertj/BUCK @@ -0,0 +1,11 @@ +prebuilt_jar( + name = 'assertj', + maven_coords = 'org.assertj:assertj-core:jar:3.11.1', + binary_jar = 'assertj-core-3.11.1.jar', + source_jar = 'assertj-core-3.11.1-sources.jar', + visibility = [ + '//java/client/test/...', + '//java/server/test/...', + ], +) + diff --git a/third_party/java/assertj/assertj-core-3.11.1-sources.jar b/third_party/java/assertj/assertj-core-3.11.1-sources.jar new file mode 100644 index 0000000000000..a8e6f9f1b810b Binary files /dev/null and b/third_party/java/assertj/assertj-core-3.11.1-sources.jar differ diff --git a/third_party/java/assertj/assertj-core-3.11.1.jar b/third_party/java/assertj/assertj-core-3.11.1.jar new file mode 100644 index 0000000000000..87e5ee380aeaa Binary files /dev/null and b/third_party/java/assertj/assertj-core-3.11.1.jar differ