From 7dc41ebc16babb0707ea922da61cc74988c731c8 Mon Sep 17 00:00:00 2001 From: Alexei Barantsev Date: Tue, 4 Apr 2017 10:38:56 +0300 Subject: [PATCH] Implementing utility method to catch expected exceptions in tests --- .../test/org/openqa/selenium/AlertsTest.java | 56 ++---- .../org/openqa/selenium/ArchitectureTest.java | 23 +-- .../openqa/selenium/ChildrenFindingTest.java | 38 +--- .../test/org/openqa/selenium/ClearTest.java | 52 ++---- .../openqa/selenium/ClickScrollingTest.java | 17 +- .../test/org/openqa/selenium/ClickTest.java | 8 +- .../test/org/openqa/selenium/CookieTest.java | 19 +- .../selenium/CorrectEventFiringTest.java | 29 ++- .../org/openqa/selenium/DimensionTest.java | 1 - .../openqa/selenium/ElementAttributeTest.java | 22 +-- .../openqa/selenium/ElementFindingTest.java | 172 ++++++++++-------- .../test/org/openqa/selenium/ErrorsTest.java | 3 - .../ExecutingAsyncJavascriptTest.java | 135 +++++--------- .../selenium/ExecutingJavascriptTest.java | 69 +++---- .../org/openqa/selenium/FormHandlingTest.java | 16 +- .../openqa/selenium/FrameSwitchingTest.java | 113 +++--------- .../org/openqa/selenium/ImplicitWaitTest.java | 28 +-- .../test/org/openqa/selenium/KeysTest.java | 10 +- .../org/openqa/selenium/ProxySettingTest.java | 33 ++-- .../test/org/openqa/selenium/ProxyTest.java | 123 ++++--------- .../org/openqa/selenium/ReferrerTest.java | 3 - .../openqa/selenium/SessionHandlingTest.java | 29 ++- .../selenium/StaleElementReferenceTest.java | 28 +-- .../org/openqa/selenium/TextPagesTest.java | 20 +- .../selenium/UnexpectedAlertBehaviorTest.java | 13 +- .../org/openqa/selenium/VisibilityTest.java | 20 +- .../openqa/selenium/WindowSwitchingTest.java | 50 ++--- .../selenium/testing/TestUtilities.java | 10 + 28 files changed, 423 insertions(+), 717 deletions(-) diff --git a/java/client/test/org/openqa/selenium/AlertsTest.java b/java/client/test/org/openqa/selenium/AlertsTest.java index f7d48e4829a1c..4a42e98b7b688 100644 --- a/java/client/test/org/openqa/selenium/AlertsTest.java +++ b/java/client/test/org/openqa/selenium/AlertsTest.java @@ -18,10 +18,10 @@ 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.junit.Assert.assertTrue; -import static org.junit.Assert.fail; import static org.junit.Assume.assumeFalse; import static org.openqa.selenium.WaitingConditions.newWindowIsOpened; import static org.openqa.selenium.support.ui.ExpectedConditions.alertIsPresent; @@ -34,6 +34,7 @@ import static org.openqa.selenium.testing.Driver.MARIONETTE; import static org.openqa.selenium.testing.Driver.PHANTOMJS; 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.isChrome; import static org.openqa.selenium.testing.TestUtilities.isFirefox; @@ -175,9 +176,8 @@ public void testSettingTheValueOfAnAlertThrows() { Alert alert = wait.until(alertIsPresent()); try { - alert.sendKeys("cheese"); - fail("Expected exception"); - } catch (ElementNotInteractableException expected) { + Throwable t = catchThrowable(() -> alert.sendKeys("cheese")); + assertThat(t, instanceOf(ElementNotInteractableException.class)); } finally { alert.accept(); } @@ -216,12 +216,8 @@ public void testAlertShouldNotAllowAdditionalCommandsIfDismissed() { Alert alert = wait.until(alertIsPresent()); alert.accept(); - try { - alert.getText(); - } catch (NoAlertPresentException expected) { - return; - } - fail("Expected NoAlertPresentException"); + Throwable t = catchThrowable(alert::getText); + assertThat(t, instanceOf(NoAlertPresentException.class)); } @JavascriptEnabled @@ -257,12 +253,8 @@ public void testShouldAllowUsersToAcceptAnAlertInANestedFrame() { @JavascriptEnabled @Test public void testSwitchingToMissingAlertThrows() throws Exception { - try { - driver.switchTo().alert(); - fail("Expected exception"); - } catch (NoAlertPresentException expected) { - // Expected - } + Throwable t = catchThrowable(() -> driver.switchTo().alert()); + assertThat(t, instanceOf(NoAlertPresentException.class)); } @JavascriptEnabled @@ -275,12 +267,8 @@ public void testSwitchingToMissingAlertInAClosedWindowThrows() throws Exception wait.until(ableToSwitchToWindow("newwindow")); driver.close(); - try { - driver.switchTo().alert(); - fail("Expected exception"); - } catch (NoSuchWindowException expected) { - // Expected - } + Throwable t = catchThrowable(() -> driver.switchTo().alert()); + assertThat(t, instanceOf(NoSuchWindowException.class)); } finally { driver.switchTo().window(mainWindow); @@ -374,14 +362,8 @@ public void testShouldNotHandleAlertInAnotherWindow() { driver.findElement(By.id("open-window-with-onload-alert")).click(); onloadWindow = wait.until(newWindowIsOpened(currentWindowHandles)); - boolean gotException = false; - try { - wait.until(alertIsPresent()); - } catch (AssertionError expected) { - // Expected - gotException = true; - } - assertTrue(gotException); + Throwable t = catchThrowable(() -> wait.until(alertIsPresent())); + assertThat(t, instanceOf(TimeoutException.class)); } finally { driver.switchTo().window(onloadWindow); @@ -479,13 +461,11 @@ public void testShouldHandleAlertOnWindowClose() { public void testIncludesAlertTextInUnhandledAlertException() { driver.findElement(By.id("alert")).click(); wait.until(alertIsPresent()); - try { - driver.getTitle(); - fail("Expected UnhandledAlertException"); - } catch (UnhandledAlertException e) { - assertEquals("cheese", e.getAlertText()); - assertThat(e.getMessage(), containsString("cheese")); - } + + Throwable t = catchThrowable(driver::getTitle); + assertThat(t, instanceOf(UnhandledAlertException.class)); + assertThat(((UnhandledAlertException) t).getAlertText(), is("cheese")); + assertThat(t.getMessage(), containsString("cheese")); } @NoDriverAfterTest diff --git a/java/client/test/org/openqa/selenium/ArchitectureTest.java b/java/client/test/org/openqa/selenium/ArchitectureTest.java index 0d743c96a431f..0987d6845e13c 100644 --- a/java/client/test/org/openqa/selenium/ArchitectureTest.java +++ b/java/client/test/org/openqa/selenium/ArchitectureTest.java @@ -19,13 +19,12 @@ 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.assertFalse; 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 static org.openqa.selenium.testing.TestUtilities.catchThrowable; import org.junit.Test; import org.junit.runner.RunWith; @@ -123,24 +122,16 @@ public void determineArchARM() { @Test public void determineArchEmpty() { - try { - Architecture.extractFromSysProperty(""); - fail("Expected UnsupportedOperationException"); - } catch (RuntimeException e) { - assertThat(e, is(instanceOf(UnsupportedOperationException.class))); - assertThat(e.getMessage(), containsString("Unknown architecture")); - } + Throwable t = catchThrowable(() -> Architecture.extractFromSysProperty("")); + assertThat(t, instanceOf(UnsupportedOperationException.class)); + assertThat(t.getMessage(), containsString("Unknown architecture")); } @Test public void determineArchBogus() { - try { - Architecture.extractFromSysProperty("hoobaflooba"); - fail("Expected UnsupportedOperationException"); - } catch (RuntimeException e) { - assertThat(e, is(instanceOf(UnsupportedOperationException.class))); - assertThat(e.getMessage(), containsString("Unknown architecture")); - } + Throwable t = catchThrowable(() -> Architecture.extractFromSysProperty("hoobaflooba")); + assertThat(t, instanceOf(UnsupportedOperationException.class)); + assertThat(t.getMessage(), containsString("Unknown architecture")); } @Test diff --git a/java/client/test/org/openqa/selenium/ChildrenFindingTest.java b/java/client/test/org/openqa/selenium/ChildrenFindingTest.java index 62ae492acd510..5de1868f721ed 100644 --- a/java/client/test/org/openqa/selenium/ChildrenFindingTest.java +++ b/java/client/test/org/openqa/selenium/ChildrenFindingTest.java @@ -18,14 +18,15 @@ 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.junit.Assert.fail; import static org.openqa.selenium.testing.Driver.CHROME; import static org.openqa.selenium.testing.Driver.IE; import static org.openqa.selenium.testing.Driver.REMOTE; +import static org.openqa.selenium.testing.TestUtilities.catchThrowable; import org.junit.Test; import org.openqa.selenium.testing.Ignore; @@ -33,7 +34,6 @@ import java.util.List; - public class ChildrenFindingTest extends JUnit4TestBase { @Test public void testFindElementByXPath() { @@ -64,14 +64,9 @@ public void testFindingDotSlashElementsOnElementByXPathShouldFindNotTopLevelElem @Test public void testFindElementByXPathWhenNoMatch() { driver.get(pages.nestedPage); - WebElement element = driver.findElement(By.name("form2")); - try { - element.findElement(By.xpath(".//select/x")); - fail("Did not expect to find element"); - } catch (NoSuchElementException ignored) { - // this is expected - } + Throwable t = catchThrowable(() -> element.findElement(By.xpath(".//select/x"))); + assertThat(t, instanceOf(NoSuchElementException.class)); } @Test @@ -141,12 +136,8 @@ public void testFindElementByIdWhenIdContainsNonAlphanumericCharacters() { public void testFindElementByIdWhenNoMatchInContext() { driver.get(pages.nestedPage); WebElement element = driver.findElement(By.id("test_id_div")); - try { - element.findElement(By.id("test_id_out")); - fail(); - } catch (NoSuchElementException e) { - // This is expected - } + Throwable t = catchThrowable(() -> element.findElement(By.id("test_id_out"))); + assertThat(t, instanceOf(NoSuchElementException.class)); } @Test @@ -290,11 +281,8 @@ public void testShouldFindGrandChildren() { public void testShouldNotFindElementOutSideTree() { driver.get(pages.formPage); WebElement element = driver.findElement(By.name("login")); - try { - element.findElement(By.name("x")); - } catch (NoSuchElementException e) { - // this is expected - } + Throwable t = catchThrowable(() -> element.findElement(By.name("x"))); + assertThat(t, instanceOf(NoSuchElementException.class)); } @Test @@ -321,8 +309,7 @@ public void testFindMultipleElements() { driver.get(pages.simpleTestPage); WebElement elem = driver.findElement(By.id("links")); - List elements = - elem.findElements(By.partialLinkText("link")); + List elements = elem.findElements(By.partialLinkText("link")); assertNotNull(elements); assertEquals(6, elements.size()); } @@ -352,12 +339,7 @@ public void testElementCanGetLinkByLinkTestIgnoringTrailingWhitespace() { driver.get(pages.simpleTestPage); WebElement elem = driver.findElement(By.id("links")); - WebElement link = null; - try { - link = elem.findElement(By.linkText("link with trailing space")); - } catch (NoSuchElementException e) { - fail("Should have found link"); - } + WebElement link = elem.findElement(By.linkText("link with trailing space")); assertEquals("linkWithTrailingSpace", link.getAttribute("id")); } diff --git a/java/client/test/org/openqa/selenium/ClearTest.java b/java/client/test/org/openqa/selenium/ClearTest.java index 8d3284318006b..2782945c39cc0 100644 --- a/java/client/test/org/openqa/selenium/ClearTest.java +++ b/java/client/test/org/openqa/selenium/ClearTest.java @@ -17,8 +17,10 @@ package org.openqa.selenium; +import static org.hamcrest.CoreMatchers.instanceOf; import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; +import static org.junit.Assert.assertThat; +import static org.openqa.selenium.testing.TestUtilities.catchThrowable; import org.junit.Test; import org.openqa.selenium.testing.JUnit4TestBase; @@ -36,26 +38,18 @@ public void testWritableTextInputShouldClear() { @Test public void testTextInputShouldNotClearWhenDisabled() { driver.get(pages.readOnlyPage); - try { - WebElement element = driver.findElement(By.id("textInputnotenabled")); - assertEquals(false, element.isEnabled()); - element.clear(); - fail("Should not have succeeded"); - } catch (InvalidElementStateException e) { - // This is expected - } + WebElement element = driver.findElement(By.id("textInputnotenabled")); + assertEquals(false, element.isEnabled()); + Throwable t = catchThrowable(element::clear); + assertThat(t, instanceOf(InvalidElementStateException.class)); } @Test public void testTextInputShouldNotClearWhenReadOnly() { - try { - driver.get(pages.readOnlyPage); - WebElement element = driver.findElement(By.id("readOnlyTextInput")); - element.clear(); - fail("Should not have succeeded"); - } catch (InvalidElementStateException e) { - // This is expected - } + driver.get(pages.readOnlyPage); + WebElement element = driver.findElement(By.id("readOnlyTextInput")); + Throwable t = catchThrowable(element::clear); + assertThat(t, instanceOf(InvalidElementStateException.class)); } @Test @@ -68,26 +62,18 @@ public void testWritableTextAreaShouldClear() { @Test public void testTextAreaShouldNotClearWhenDisabled() { - try { - driver.get(pages.readOnlyPage); - WebElement element = driver.findElement(By.id("textAreaNotenabled")); - element.clear(); - fail("Should not have succeeded"); - } catch (InvalidElementStateException e) { - // This is expected - } + driver.get(pages.readOnlyPage); + WebElement element = driver.findElement(By.id("textAreaNotenabled")); + Throwable t = catchThrowable(element::clear); + assertThat(t, instanceOf(InvalidElementStateException.class)); } @Test public void testTextAreaShouldNotClearWhenReadOnly() { - try { - driver.get(pages.readOnlyPage); - WebElement element = driver.findElement(By.id("textAreaReadOnly")); - element.clear(); - fail("Should not have succeeded"); - } catch (InvalidElementStateException e) { - // This is expected - } + driver.get(pages.readOnlyPage); + WebElement element = driver.findElement(By.id("textAreaReadOnly")); + Throwable t = catchThrowable(element::clear); + assertThat(t, instanceOf(InvalidElementStateException.class)); } @Test diff --git a/java/client/test/org/openqa/selenium/ClickScrollingTest.java b/java/client/test/org/openqa/selenium/ClickScrollingTest.java index 9ffc7bbd88e67..9c4a53cd9c50d 100644 --- a/java/client/test/org/openqa/selenium/ClickScrollingTest.java +++ b/java/client/test/org/openqa/selenium/ClickScrollingTest.java @@ -18,11 +18,11 @@ 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.junit.Assert.fail; import static org.openqa.selenium.support.ui.ExpectedConditions.titleIs; import static org.openqa.selenium.testing.Driver.CHROME; import static org.openqa.selenium.testing.Driver.HTMLUNIT; @@ -30,6 +30,7 @@ import static org.openqa.selenium.testing.Driver.MARIONETTE; import static org.openqa.selenium.testing.Driver.PHANTOMJS; 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; @@ -57,8 +58,7 @@ public void testClickingOnAnchorScrollsPage() { driver.findElement(By.partialLinkText("last speech")).click(); - long yOffset = (Long) ((JavascriptExecutor) driver) - .executeScript(scrollScript); + long yOffset = (Long) ((JavascriptExecutor) driver).executeScript(scrollScript); // Focusing on to click, but not actually following, // the link will scroll it in to view, which is a few pixels further than 0 @@ -71,11 +71,7 @@ public void testShouldScrollToClickOnAnElementHiddenByOverflow() { driver.get(url); WebElement link = driver.findElement(By.id("link")); - try { - link.click(); - } catch (MoveTargetOutOfBoundsException e) { - fail("Should not be out of bounds: " + e.getMessage()); - } + link.click(); } @Test @@ -172,13 +168,14 @@ public void testShouldBeAbleToClickElementThatIsOutOfViewInAFrame() { } @SwitchToTopAfterTest - @Test(expected = MoveTargetOutOfBoundsException.class) + @Test @Ignore(reason = "All tested browses scroll non-scrollable frames") public void testShouldNotBeAbleToClickElementThatIsOutOfViewInANonScrollableFrame() { 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")); - element.click(); + Throwable t = catchThrowable(element::click); + assertThat(t, instanceOf(MoveTargetOutOfBoundsException.class)); } @SwitchToTopAfterTest diff --git a/java/client/test/org/openqa/selenium/ClickTest.java b/java/client/test/org/openqa/selenium/ClickTest.java index b4d1410bcdc70..9c1eae0e18385 100644 --- a/java/client/test/org/openqa/selenium/ClickTest.java +++ b/java/client/test/org/openqa/selenium/ClickTest.java @@ -35,7 +35,6 @@ import org.junit.Before; import org.junit.Test; -import org.openqa.selenium.interactions.MoveTargetOutOfBoundsException; import org.openqa.selenium.testing.Ignore; import org.openqa.selenium.testing.JUnit4TestBase; import org.openqa.selenium.testing.JavascriptEnabled; @@ -235,12 +234,7 @@ public void testShouldBeAbleToClickOnAnElementInTheViewport() { driver.get(url); WebElement button = driver.findElement(By.id("button")); - - try { - button.click(); - } catch (MoveTargetOutOfBoundsException e) { - fail("Should not be out of bounds: " + e.getMessage()); - } + button.click(); } @Test diff --git a/java/client/test/org/openqa/selenium/CookieTest.java b/java/client/test/org/openqa/selenium/CookieTest.java index 910688e8cf678..296ad56f23a6d 100644 --- a/java/client/test/org/openqa/selenium/CookieTest.java +++ b/java/client/test/org/openqa/selenium/CookieTest.java @@ -18,10 +18,11 @@ 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.junit.Assert.fail; +import static org.openqa.selenium.testing.TestUtilities.catchThrowable; import org.junit.Test; import org.junit.runner.RunWith; @@ -45,23 +46,15 @@ public void testCanCreateAWellFormedCookie() { @Test public void testShouldThrowAnExceptionWhenSemiColonExistsInTheCookieAttribute() { Cookie cookie = new Cookie("hi;hi", "value", null, null, null, false); - try { - cookie.validate(); - fail(); - } catch (IllegalArgumentException e) { - // Expected - } + Throwable t = catchThrowable(cookie::validate); + assertThat(t, instanceOf(IllegalArgumentException.class)); } @Test public void testShouldThrowAnExceptionTheNameIsNull() { Cookie cookie = new Cookie(null, "value", null, null, null, false); - try { - cookie.validate(); - fail(); - } catch (IllegalArgumentException e) { - // expected - } + Throwable t = catchThrowable(cookie::validate); + assertThat(t, instanceOf(IllegalArgumentException.class)); } @Test diff --git a/java/client/test/org/openqa/selenium/CorrectEventFiringTest.java b/java/client/test/org/openqa/selenium/CorrectEventFiringTest.java index ada10eaac38b0..87000d9304a62 100644 --- a/java/client/test/org/openqa/selenium/CorrectEventFiringTest.java +++ b/java/client/test/org/openqa/selenium/CorrectEventFiringTest.java @@ -17,7 +17,10 @@ package org.openqa.selenium; +import static org.hamcrest.Matchers.contains; +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; @@ -37,6 +40,7 @@ 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; @@ -204,11 +208,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(), equalTo(initialTextValue)); bar.click(); - assertThat(driver.findElement(By.id("result")).getText(), - equalTo("bar")); + assertThat(driver.findElement(By.id("result")).getText(), equalTo("bar")); } @JavascriptEnabled @@ -222,11 +224,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(), equalTo("foo")); bar.click(); - assertThat(driver.findElement(By.id("result")).getText(), - equalTo("bar")); + assertThat(driver.findElement(By.id("result")).getText(), equalTo("bar")); } @JavascriptEnabled @@ -439,15 +439,10 @@ public void testClickEventsShouldBubble() { public void testClickOverlappingElements() { assumeFalse(isOldIe(driver)); driver.get(appServer.whereIs("click_tests/overlapping_elements.html")); - try { - driver.findElement(By.id("under")).click(); - } catch (WebDriverException expected) { - if (expected.getMessage().contains("Other element would receive the click")) { - return; - } - expected.printStackTrace(); - } - fail("Should have thrown Exception with 'Other element would receive the click' in the message"); + WebElement element = driver.findElement(By.id("under")); + Throwable t = catchThrowable(element::click); + assertThat(t, instanceOf(WebDriverException.class)); + assertThat(t.getMessage(), containsString("Other element would receive the click")); } @JavascriptEnabled diff --git a/java/client/test/org/openqa/selenium/DimensionTest.java b/java/client/test/org/openqa/selenium/DimensionTest.java index f5e946cfbd2f6..764cd8b538678 100644 --- a/java/client/test/org/openqa/selenium/DimensionTest.java +++ b/java/client/test/org/openqa/selenium/DimensionTest.java @@ -52,5 +52,4 @@ public void testEquality() { assertEquals(d1.hashCode(), d1copy.hashCode()); } - } diff --git a/java/client/test/org/openqa/selenium/ElementAttributeTest.java b/java/client/test/org/openqa/selenium/ElementAttributeTest.java index 1f7bee5b31cdb..d1c2d0ef7cdc8 100644 --- a/java/client/test/org/openqa/selenium/ElementAttributeTest.java +++ b/java/client/test/org/openqa/selenium/ElementAttributeTest.java @@ -20,6 +20,7 @@ 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; @@ -28,10 +29,10 @@ 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.assumeFalse; import static org.openqa.selenium.testing.Driver.HTMLUNIT; import static org.openqa.selenium.testing.Driver.MARIONETTE; +import static org.openqa.selenium.testing.TestUtilities.catchThrowable; import org.junit.Test; import org.openqa.selenium.support.ui.ExpectedConditions; @@ -133,21 +134,13 @@ public void testElementsShouldBeDisabledIfTheyAreDisabledUsingRandomDisabledStri public void testShouldThrowExceptionIfSendingKeysToElementDisabledUsingRandomDisabledStrings() { driver.get(pages.formPage); WebElement disabledTextElement1 = driver.findElement(By.id("disabledTextElement1")); - try { - disabledTextElement1.sendKeys("foo"); - fail("Should have thrown exception"); - } catch (InvalidElementStateException e) { - // Expected - } + Throwable t = catchThrowable(() -> disabledTextElement1.sendKeys("foo")); + assertThat(t, instanceOf(InvalidElementStateException.class)); assertThat(disabledTextElement1.getText(), is("")); WebElement disabledTextElement2 = driver.findElement(By.id("disabledTextElement2")); - try { - disabledTextElement2.sendKeys("bar"); - fail("Should have thrown exception"); - } catch (InvalidElementStateException e) { - // Expected - } + Throwable t2 = catchThrowable(() -> disabledTextElement2.sendKeys("bar")); + assertThat(t2, instanceOf(InvalidElementStateException.class)); assertThat(disabledTextElement2.getText(), is("")); } @@ -286,8 +279,7 @@ public void testShouldCorrectlyReportValueOfColspan() { try { Thread.sleep(1000); } catch (InterruptedException e) { - e.printStackTrace(); // To change body of catch statement use File | Settings | File - // Templates. + e.printStackTrace(); } WebElement th1 = driver.findElement(By.id("th1")); diff --git a/java/client/test/org/openqa/selenium/ElementFindingTest.java b/java/client/test/org/openqa/selenium/ElementFindingTest.java index 80f78d5d6dd9c..236f168ac7efb 100644 --- a/java/client/test/org/openqa/selenium/ElementFindingTest.java +++ b/java/client/test/org/openqa/selenium/ElementFindingTest.java @@ -19,11 +19,11 @@ 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.junit.Assert.fail; import static org.junit.Assume.assumeFalse; import static org.openqa.selenium.testing.Driver.CHROME; import static org.openqa.selenium.testing.Driver.HTMLUNIT; @@ -31,6 +31,7 @@ import static org.openqa.selenium.testing.Driver.MARIONETTE; import static org.openqa.selenium.testing.Driver.REMOTE; 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; @@ -102,10 +103,11 @@ public void testShouldBeAbleToFindMultipleElementsByIdWithNonAlphanumericCharact // By.id negative - @Test(expected = NoSuchElementException.class) + @Test public void testShouldNotBeAbleToLocateByIdASingleElementThatDoesNotExist() { driver.get(pages.formPage); - driver.findElement(By.id("nonExistentButton")); + Throwable t = catchThrowable(() -> driver.findElement(By.id("nonExistentButton"))); + assertThat(t, instanceOf(NoSuchElementException.class)); } @Test @@ -115,10 +117,11 @@ public void testShouldNotBeAbleToLocateByIdMultipleElementsThatDoNotExist() { assertThat(elements.size(), is(0)); } - @Test(expected = NoSuchElementException.class) + @Test public void testFindingASingleElementByEmptyIdShouldThrow() { driver.get(pages.formPage); - driver.findElement(By.id("")); + Throwable t = catchThrowable(() -> driver.findElement(By.id(""))); + assertThat(t, instanceOf(NoSuchElementException.class)); } @Test @@ -129,10 +132,11 @@ public void testFindingMultipleElementsByEmptyIdShouldReturnEmptyList() { assertThat(elements.size(), is(0)); } - @Test(expected = NoSuchElementException.class) + @Test public void testFindingASingleElementByIdWithSpaceShouldThrow() { driver.get(pages.formPage); - driver.findElement(By.id("nonexistent button")); + Throwable t = catchThrowable(() -> driver.findElement(By.id("nonexistent button"))); + assertThat(t, instanceOf(NoSuchElementException.class)); } @Test @@ -167,10 +171,11 @@ public void testShouldBeAbleToFindAnElementThatDoesNotSupportTheNameProperty() { // By.name negative - @Test(expected = NoSuchElementException.class) + @Test public void testShouldNotBeAbleToLocateByNameASingleElementThatDoesNotExist() { driver.get(pages.formPage); - driver.findElement(By.name("nonExistentButton")); + Throwable t = catchThrowable(() -> driver.findElement(By.name("nonExistentButton"))); + assertThat(t, instanceOf(NoSuchElementException.class)); } @Test @@ -180,10 +185,11 @@ public void testShouldNotBeAbleToLocateByNameMultipleElementsThatDoNotExist() { assertThat(elements.size(), is(0)); } - @Test(expected = NoSuchElementException.class) + @Test public void testFindingASingleElementByEmptyNameShouldThrow() { driver.get(pages.formPage); - driver.findElement(By.name("")); + Throwable t = catchThrowable(() -> driver.findElement(By.name(""))); + assertThat(t, instanceOf(NoSuchElementException.class)); } @Test @@ -193,10 +199,11 @@ public void testFindingMultipleElementsByEmptyNameShouldReturnEmptyList() { assertThat(elements.size(), is(0)); } - @Test(expected = NoSuchElementException.class) + @Test public void testFindingASingleElementByNameWithSpaceShouldThrow() { driver.get(pages.formPage); - driver.findElement(By.name("nonexistent button")); + Throwable t = catchThrowable(() -> driver.findElement(By.name("nonexistent button"))); + assertThat(t, instanceOf(NoSuchElementException.class)); } @Test @@ -224,10 +231,11 @@ public void testShouldBeAbleToFindMultipleElementsByTagName() { // By.tagName negative - @Test(expected = NoSuchElementException.class) + @Test public void testShouldNotBeAbleToLocateByTagNameASingleElementThatDoesNotExist() { driver.get(pages.formPage); - driver.findElement(By.tagName("nonExistentButton")); + Throwable t = catchThrowable(() -> driver.findElement(By.tagName("nonExistentButton"))); + assertThat(t, instanceOf(NoSuchElementException.class)); } @Test @@ -237,22 +245,25 @@ public void testShouldNotBeAbleToLocateByTagNameMultipleElementsThatDoNotExist() assertThat(elements.size(), is(0)); } - @Test(expected = NoSuchElementException.class) + @Test public void testFindingASingleElementByEmptyTagNameShouldThrow() { driver.get(pages.formPage); - driver.findElement(By.tagName("")); + Throwable t = catchThrowable(() -> driver.findElement(By.tagName(""))); + assertThat(t, instanceOf(NoSuchElementException.class)); } - @Test(expected = NoSuchElementException.class) + @Test public void testFindingMultipleElementsByEmptyTagNameShouldThrow() { driver.get(pages.formPage); - driver.findElements(By.tagName("")); + Throwable t = catchThrowable(() -> driver.findElements(By.tagName(""))); + assertThat(t, instanceOf(NoSuchElementException.class)); } - @Test(expected = NoSuchElementException.class) + @Test public void testFindingASingleElementByTagNameWithSpaceShouldThrow() { driver.get(pages.formPage); - driver.findElement(By.tagName("nonexistent button")); + Throwable t = catchThrowable(() -> driver.findElement(By.tagName("nonexistent button"))); + assertThat(t, instanceOf(NoSuchElementException.class)); } @Test @@ -316,48 +327,55 @@ public void testShouldFindElementsByClassWhenItsNameIsSurroundedByWhitespace() { // By.className negative - @Test(expected = NoSuchElementException.class) + @Test public void testShouldNotFindElementByClassWhenTheNameQueriedIsShorterThanCandidateName() { driver.get(pages.xhtmlTestPage); - driver.findElement(By.className("nameB")); + Throwable t = catchThrowable(() -> driver.findElement(By.className("nameB"))); + assertThat(t, instanceOf(NoSuchElementException.class)); } - @Test(expected = NoSuchElementException.class) + @Test public void testFindingASingleElementByEmptyClassNameShouldThrow() { driver.get(pages.xhtmlTestPage); - driver.findElement(By.className("")); + Throwable t = catchThrowable(() -> driver.findElement(By.className(""))); + assertThat(t, instanceOf(NoSuchElementException.class)); } - @Test(expected = NoSuchElementException.class) + @Test public void testFindingMultipleElementsByEmptyClassNameShouldThrow() { driver.get(pages.xhtmlTestPage); - driver.findElements(By.className("")); + Throwable t = catchThrowable(() -> driver.findElements(By.className(""))); + assertThat(t, instanceOf(NoSuchElementException.class)); } - @Test(expected = NoSuchElementException.class) + @Test public void testFindingASingleElementByCompoundClassNameShouldThrow() { driver.get(pages.xhtmlTestPage); - driver.findElement(By.className("a b")); + Throwable t = catchThrowable(() -> driver.findElement(By.className("a b"))); + assertThat(t, instanceOf(NoSuchElementException.class)); } + @Test @Ignore(value = {MARIONETTE}) - @Test(expected = NoSuchElementException.class) public void testFindingMultipleElementsByCompoundClassNameShouldThrow() { driver.get(pages.xhtmlTestPage); - driver.findElements(By.className("a b")); + Throwable t = catchThrowable(() -> driver.findElements(By.className("a b"))); + assertThat(t, instanceOf(NoSuchElementException.class)); } - @Test(expected = NoSuchElementException.class) + @Test public void testFindingASingleElementByInvalidClassNameShouldThrow() { driver.get(pages.xhtmlTestPage); - driver.findElement(By.className("!@#$%^&*")); + Throwable t = catchThrowable(() -> driver.findElement(By.className("!@#$%^&*"))); + assertThat(t, instanceOf(NoSuchElementException.class)); } + @Test @Ignore(value = {MARIONETTE}) - @Test(expected = NoSuchElementException.class) public void testFindingMultipleElementsByInvalidClassNameShouldThrow() { driver.get(pages.xhtmlTestPage); - driver.findElements(By.className("!@#$%^&*")); + Throwable t = catchThrowable(() -> driver.findElements(By.className("!@#$%^&*"))); + assertThat(t, instanceOf(NoSuchElementException.class)); } // By.xpath positive @@ -435,71 +453,80 @@ public void testShouldBeAbleToFindElementByXPathInXmlDocument() { // By.xpath negative - @Test(expected = NoSuchElementException.class) + @Test public void testShouldThrowAnExceptionWhenThereIsNoLinkToClick() { driver.get(pages.xhtmlTestPage); - driver.findElement(By.xpath("//a[@id='Not here']")); + Throwable t = catchThrowable(() -> driver.findElement(By.xpath("//a[@id='Not here']"))); + assertThat(t, instanceOf(NoSuchElementException.class)); } - @Test(expected = InvalidSelectorException.class) + @Test public void testShouldThrowInvalidSelectorExceptionWhenXPathIsSyntacticallyInvalidInDriverFindElement() { driver.get(pages.formPage); - driver.findElement(By.xpath("this][isnot][valid")); + Throwable t = catchThrowable(() -> driver.findElement(By.xpath("this][isnot][valid"))); + assertThat(t, instanceOf(InvalidSelectorException.class)); } - @Test(expected = InvalidSelectorException.class) + @Test public void testShouldThrowInvalidSelectorExceptionWhenXPathIsSyntacticallyInvalidInDriverFindElements() { assumeFalse("Ignoring xpath error test in IE6", TestUtilities.isIe6(driver)); driver.get(pages.formPage); - driver.findElements(By.xpath("this][isnot][valid")); + Throwable t = catchThrowable(() -> driver.findElements(By.xpath("this][isnot][valid"))); + assertThat(t, instanceOf(InvalidSelectorException.class)); } - @Test(expected = InvalidSelectorException.class) + @Test public void testShouldThrowInvalidSelectorExceptionWhenXPathIsSyntacticallyInvalidInElementFindElement() { driver.get(pages.formPage); WebElement body = driver.findElement(By.tagName("body")); - body.findElement(By.xpath("this][isnot][valid")); + Throwable t = catchThrowable(() -> body.findElement(By.xpath("this][isnot][valid"))); + assertThat(t, instanceOf(InvalidSelectorException.class)); } - @Test(expected = InvalidSelectorException.class) + @Test public void testShouldThrowInvalidSelectorExceptionWhenXPathIsSyntacticallyInvalidInElementFindElements() { assumeFalse("Ignoring xpath error test in IE6", TestUtilities.isIe6(driver)); driver.get(pages.formPage); WebElement body = driver.findElement(By.tagName("body")); - body.findElements(By.xpath("this][isnot][valid")); + Throwable t = catchThrowable(() -> body.findElements(By.xpath("this][isnot][valid"))); + assertThat(t, instanceOf(InvalidSelectorException.class)); } - @Test(expected = InvalidSelectorException.class) + @Test public void testShouldThrowInvalidSelectorExceptionWhenXPathReturnsWrongTypeInDriverFindElement() { driver.get(pages.formPage); - driver.findElement(By.xpath("count(//input)")); + Throwable t = catchThrowable(() -> driver.findElement(By.xpath("count(//input)"))); + assertThat(t, instanceOf(InvalidSelectorException.class)); } - @Test(expected = InvalidSelectorException.class) + @Test public void testShouldThrowInvalidSelectorExceptionWhenXPathReturnsWrongTypeInDriverFindElements() { assumeFalse("Ignoring xpath error test in IE6", TestUtilities.isIe6(driver)); driver.get(pages.formPage); - driver.findElements(By.xpath("count(//input)")); + Throwable t = catchThrowable(() -> driver.findElements(By.xpath("count(//input)"))); + assertThat(t, instanceOf(InvalidSelectorException.class)); } - @Test(expected = InvalidSelectorException.class) + @Test public void testShouldThrowInvalidSelectorExceptionWhenXPathReturnsWrongTypeInElementFindElement() { driver.get(pages.formPage); WebElement body = driver.findElement(By.tagName("body")); - body.findElement(By.xpath("count(//input)")); + Throwable t = catchThrowable(() -> body.findElement(By.xpath("count(//input)"))); + assertThat(t, instanceOf(InvalidSelectorException.class)); } - @Test(expected = InvalidSelectorException.class) + @Test public void testShouldThrowInvalidSelectorExceptionWhenXPathReturnsWrongTypeInElementFindElements() { assumeFalse("Ignoring xpath error test in IE6", TestUtilities.isIe6(driver)); driver.get(pages.formPage); WebElement body = driver.findElement(By.tagName("body")); - body.findElements(By.xpath("count(//input)")); + Throwable t = catchThrowable(() -> body.findElements(By.xpath("count(//input)"))); + assertThat(t, instanceOf(InvalidSelectorException.class)); } // By.cssSelector positive @@ -560,41 +587,47 @@ public void testShouldBeAbleToFindAnElementByBooleanAttributeUsingShortCssSelect // By.cssSelector negative - @Test(expected = NoSuchElementException.class) + @Test public void testShouldNotFindElementByCssSelectorWhenThereIsNoSuchElement() { driver.get(pages.xhtmlTestPage); - driver.findElement(By.cssSelector(".there-is-no-such-class")); + Throwable t = catchThrowable(() -> driver.findElement(By.cssSelector(".there-is-no-such-class"))); + assertThat(t, instanceOf(NoSuchElementException.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)); } - @Test(expected = NoSuchElementException.class) + @Test public void testFindingASingleElementByEmptyCssSelectorShouldThrow() { driver.get(pages.xhtmlTestPage); - driver.findElement(By.cssSelector("")); + Throwable t = catchThrowable(() -> driver.findElement(By.cssSelector(""))); + assertThat(t, instanceOf(NoSuchElementException.class)); } - @Test(expected = NoSuchElementException.class) + @Test public void testFindingMultipleElementsByEmptyCssSelectorShouldThrow() { driver.get(pages.xhtmlTestPage); - driver.findElements(By.cssSelector("")); + Throwable t = catchThrowable(() -> driver.findElements(By.cssSelector(""))); + assertThat(t, instanceOf(NoSuchElementException.class)); } - @Test(expected = NoSuchElementException.class) + @Test public void testFindingASingleElementByInvalidCssSelectorShouldThrow() { driver.get(pages.xhtmlTestPage); - driver.findElement(By.cssSelector("//a/b/c[@id='1']")); + Throwable t = catchThrowable(() -> driver.findElement(By.cssSelector("//a/b/c[@id='1']"))); + assertThat(t, instanceOf(NoSuchElementException.class)); } - @Test(expected = NoSuchElementException.class) + @Test public void testFindingMultipleElementsByInvalidCssSelectorShouldThrow() { assumeFalse("Ignoring test for lack of error in CSS in IE6", TestUtilities.isIe6(driver)); driver.get(pages.xhtmlTestPage); - driver.findElements(By.cssSelector("//a/b/c[@id='1']")); + Throwable t = catchThrowable(() -> driver.findElements(By.cssSelector("//a/b/c[@id='1']"))); + assertThat(t, instanceOf(NoSuchElementException.class)); } // By.linkText positive @@ -659,10 +692,11 @@ public void testDriverCanGetLinkByLinkTestIgnoringTrailingWhitespace() { // By.linkText negative - @Test(expected = NoSuchElementException.class) + @Test public void testShouldNotBeAbleToLocateByLinkTextASingleElementThatDoesNotExist() { driver.get(pages.xhtmlTestPage); - driver.findElement(By.linkText("Not here either")); + Throwable t = catchThrowable(() -> driver.findElement(By.linkText("Not here either"))); + assertThat(t, instanceOf(NoSuchElementException.class)); } @Test @@ -758,12 +792,8 @@ public void testAnElementFoundInADifferentFrameIsStale() { driver.switchTo().frame("inner"); WebElement element = driver.findElement(By.id("oneline")); driver.switchTo().defaultContent(); - try { - element.getText(); - fail("Expected exception"); - } catch (StaleElementReferenceException expected) { - // Expected - } + Throwable t = catchThrowable(element::getText); + assertThat(t, instanceOf(StaleElementReferenceException.class)); } @JavascriptEnabled diff --git a/java/client/test/org/openqa/selenium/ErrorsTest.java b/java/client/test/org/openqa/selenium/ErrorsTest.java index ff3fa9bbf8d09..ce613202159dd 100644 --- a/java/client/test/org/openqa/selenium/ErrorsTest.java +++ b/java/client/test/org/openqa/selenium/ErrorsTest.java @@ -25,9 +25,6 @@ import org.openqa.selenium.testing.JUnit4TestBase; import org.openqa.selenium.testing.JavascriptEnabled; -/** - * @author jmleyba@gmail.com (Jason Leyba) - */ public class ErrorsTest extends JUnit4TestBase { /** diff --git a/java/client/test/org/openqa/selenium/ExecutingAsyncJavascriptTest.java b/java/client/test/org/openqa/selenium/ExecutingAsyncJavascriptTest.java index a8a746ac9c317..84823146739f4 100644 --- a/java/client/test/org/openqa/selenium/ExecutingAsyncJavascriptTest.java +++ b/java/client/test/org/openqa/selenium/ExecutingAsyncJavascriptTest.java @@ -20,13 +20,13 @@ 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.junit.Assert.fail; import static org.junit.Assume.assumeTrue; import static org.openqa.selenium.testing.Driver.CHROME; import static org.openqa.selenium.testing.Driver.HTMLUNIT; @@ -34,6 +34,7 @@ import static org.openqa.selenium.testing.Driver.MARIONETTE; import static org.openqa.selenium.testing.Driver.PHANTOMJS; import static org.openqa.selenium.testing.Driver.SAFARI; +import static org.openqa.selenium.testing.TestUtilities.catchThrowable; import com.google.common.base.Throwables; @@ -164,13 +165,9 @@ public void shouldBeAbleToReturnArraysOfWebElementsFromAsyncScripts() { @Ignore(value = {HTMLUNIT}) public void shouldTimeoutIfScriptDoesNotInvokeCallback() { driver.get(pages.ajaxyPage); - try { - // Script is expected to be async and explicitly callback, so this should timeout. - executor.executeAsyncScript("return 1 + 2;"); - fail("Should have thrown a TimeOutException!"); - } catch (ScriptTimeoutException exception) { - // Do nothing. - } + // 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)); } @JavascriptEnabled @@ -178,12 +175,9 @@ public void shouldTimeoutIfScriptDoesNotInvokeCallback() { @Ignore(value = {HTMLUNIT}) public void shouldTimeoutIfScriptDoesNotInvokeCallbackWithAZeroTimeout() { driver.get(pages.ajaxyPage); - try { - executor.executeAsyncScript("window.setTimeout(function() {}, 0);"); - fail("Should have thrown a TimeOutException!"); - } catch (ScriptTimeoutException exception) { - // Do nothing. - } + Throwable t = catchThrowable( + () -> executor.executeAsyncScript("window.setTimeout(function() {}, 0);")); + assertThat(t, instanceOf(ScriptTimeoutException.class)); } @JavascriptEnabled @@ -201,14 +195,10 @@ public void shouldNotTimeoutIfScriptCallsbackInsideAZeroTimeout() { public void shouldTimeoutIfScriptDoesNotInvokeCallbackWithLongTimeout() { driver.manage().timeouts().setScriptTimeout(500, TimeUnit.MILLISECONDS); driver.get(pages.ajaxyPage); - try { - executor.executeAsyncScript( - "var callback = arguments[arguments.length - 1];" + - "window.setTimeout(callback, 1500);"); - fail("Should have thrown a TimeOutException!"); - } catch (ScriptTimeoutException exception) { - // Do nothing. - } + Throwable t = catchThrowable(() -> executor.executeAsyncScript( + "var callback = arguments[arguments.length - 1];" + + "window.setTimeout(callback, 1500);")); + assertThat(t, instanceOf(ScriptTimeoutException.class)); } @JavascriptEnabled @@ -217,22 +207,18 @@ public void shouldTimeoutIfScriptDoesNotInvokeCallbackWithLongTimeout() { public void shouldDetectPageLoadsWhileWaitingOnAnAsyncScriptAndReturnAnError() { driver.get(pages.ajaxyPage); driver.manage().timeouts().setScriptTimeout(100, TimeUnit.MILLISECONDS); - try { - executor.executeAsyncScript("window.location = '" + pages.dynamicPage + "';"); - fail(); - } catch (WebDriverException expected) { - } + Throwable t = catchThrowable( + () -> executor.executeAsyncScript("window.location = '" + pages.dynamicPage + "';")); + assertThat(t, instanceOf(WebDriverException.class)); } @JavascriptEnabled @Test public void shouldCatchErrorsWhenExecutingInitialScript() { driver.get(pages.ajaxyPage); - try { - executor.executeAsyncScript("throw Error('you should catch this!');"); - fail(); - } catch (WebDriverException expected) { - } + Throwable t = catchThrowable( + () -> executor.executeAsyncScript("throw Error('you should catch this!');")); + assertThat(t, instanceOf(WebDriverException.class)); } @JavascriptEnabled @@ -254,24 +240,21 @@ public void shouldCatchErrorsWithMessageAndStacktraceWhenExecutingInitialScript( String js = "function functionB() { throw Error('errormessage'); };" + "function functionA() { functionB(); };" + "functionA();"; - try { - executor.executeAsyncScript(js); - fail("Expected an exception"); - } catch (WebDriverException e) { - assertThat(e.getMessage(), containsString("errormessage")); - - Throwable rootCause = Throwables.getRootCause(e); - assertThat(rootCause.getMessage(), containsString("errormessage")); - - StackTraceElement [] st = rootCause.getStackTrace(); - boolean seen = false; - for (StackTraceElement s: st) { - if (s.getMethodName().equals("functionB")) { - seen = true; - } + 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); } + assertTrue("Stacktrace has not js method info", seen); } @JavascriptEnabled @@ -304,8 +287,8 @@ public void shouldBeAbleToExecuteAsynchronousScripts() { @Test public void shouldBeAbleToPassMultipleArgumentsToAsyncScripts() { driver.get(pages.ajaxyPage); - Number result = (Number) ((JavascriptExecutor) driver) - .executeAsyncScript("arguments[arguments.length - 1](arguments[0] + arguments[1]);", 1, 2); + Number result = (Number) executor.executeAsyncScript( + "arguments[arguments.length - 1](arguments[0] + arguments[1]);", 1, 2); assertEquals(3, result.intValue()); } @@ -338,8 +321,7 @@ public void shouldBeAbleToMakeXMLHttpRequestsAndWaitForTheResponse() { driver.get(pages.ajaxyPage); driver.manage().timeouts().setScriptTimeout(3, TimeUnit.SECONDS); - String response = (String) ((JavascriptExecutor) driver) - .executeAsyncScript(script, pages.sleepingPage + "?time=2"); + String response = (String) executor.executeAsyncScript(script, pages.sleepingPage + "?time=2"); assertThat(response.trim(), equalTo("DoneSlept for 2s")); } @@ -352,13 +334,9 @@ public void shouldBeAbleToMakeXMLHttpRequestsAndWaitForTheResponse() { 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 - } + Throwable t = catchThrowable(() -> executor.executeAsyncScript( + "setTimeout(arguments[0], 200) ; setTimeout(function() { window.alert('Look! An alert!'); }, 50);")); + assertThat(t, instanceOf(UnhandledAlertException.class)); // Shouldn't throw driver.getTitle(); } @@ -371,12 +349,8 @@ public void throwsIfScriptTriggersAlert() { 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 - } + Throwable t = catchThrowable(() -> executor.executeAsyncScript("setTimeout(arguments[0], 1000);")); + assertThat(t, instanceOf(UnhandledAlertException.class)); // Shouldn't throw driver.getTitle(); } @@ -388,13 +362,9 @@ public void throwsIfAlertHappensDuringScript() { 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 - } + Throwable t = catchThrowable(() -> executor.executeAsyncScript( + "setTimeout(function() { window.alert('Look! An alert!'); }, 50);")); + assertThat(t, instanceOf(UnhandledAlertException.class)); // Shouldn't throw driver.getTitle(); } @@ -407,12 +377,8 @@ public void throwsIfScriptTriggersAlertWhichTimesOut() { 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 - } + Throwable t = catchThrowable(() -> executor.executeAsyncScript("")); + assertThat(t, instanceOf(UnhandledAlertException.class)); // Shouldn't throw driver.getTitle(); } @@ -425,14 +391,11 @@ public void throwsIfAlertHappensDuringScriptWhichTimesOut() { public void includesAlertTextInUnhandledAlertException() { driver.manage().timeouts().setScriptTimeout(5000, TimeUnit.MILLISECONDS); String alertText = "Look! An alert!"; - try { - ((JavascriptExecutor) driver).executeAsyncScript( - "setTimeout(arguments[0], 200) ; setTimeout(function() { window.alert('" + alertText - + "'); }, 50);"); - fail("Expected UnhandledAlertException"); - } catch (UnhandledAlertException e) { - assertEquals(alertText, e.getAlertText()); - } + 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)); } private long getNumDivElements() { diff --git a/java/client/test/org/openqa/selenium/ExecutingJavascriptTest.java b/java/client/test/org/openqa/selenium/ExecutingJavascriptTest.java index 18dd03f87e618..51036a8895e80 100644 --- a/java/client/test/org/openqa/selenium/ExecutingJavascriptTest.java +++ b/java/client/test/org/openqa/selenium/ExecutingJavascriptTest.java @@ -21,6 +21,8 @@ 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; @@ -35,6 +37,7 @@ import static org.openqa.selenium.testing.Driver.MARIONETTE; import static org.openqa.selenium.testing.Driver.PHANTOMJS; 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; @@ -276,13 +279,9 @@ public void testPassingAndReturningADoubleShouldReturnADecimal() { public void testShouldThrowAnExceptionWhenTheJavascriptIsBad() { driver.get(pages.xhtmlTestPage); - try { - executeScript("return squiggle();"); - fail("Expected an exception"); - } catch (WebDriverException e) { - // This is expected - assertFalse(e.getMessage(), e.getMessage().startsWith("null ")); - } + Throwable t = catchThrowable(() -> executeScript("return squiggle();")); + assertThat(t, instanceOf(WebDriverException.class)); + assertThat(t.getMessage(), not(startsWith("null "))); } @JavascriptEnabled @@ -295,24 +294,21 @@ public void testShouldThrowAnExceptionWithMessageAndStacktraceWhenTheJavascriptI String js = "function functionB() { throw Error('errormessage'); };" + "function functionA() { functionB(); };" + "functionA();"; - try { - executeScript(js); - fail("Expected an exception"); - } catch (WebDriverException e) { - assertThat(e.getMessage(), containsString("errormessage")); - - Throwable rootCause = Throwables.getRootCause(e); - assertThat(rootCause.getMessage(), containsString("errormessage")); - - StackTraceElement [] st = rootCause.getStackTrace(); - boolean seen = false; - for (StackTraceElement s: st) { - if (s.getMethodName().equals("functionB")) { - seen = true; - } + 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); } + assertTrue("Stacktrace has not js method info", seen); } @JavascriptEnabled @@ -408,12 +404,8 @@ public void testShouldBeAbleToPassACollectionAsArgument() { @Test public void testShouldThrowAnExceptionIfAnArgumentIsNotValid() { driver.get(pages.javascriptPage); - try { - executeScript("return arguments[0];", driver); - fail("Exception should have been thrown"); - } catch (IllegalArgumentException e) { - // this is expected - } + Throwable t = catchThrowable(() -> executeScript("return arguments[0];", driver)); + assertThat(t, instanceOf(IllegalArgumentException.class)); } @JavascriptEnabled @@ -496,13 +488,8 @@ public void testShouldBeAbleToExecuteScriptAndReturnElementsList() { " test suite. Really needs a timeout set.") @Test public void testShouldThrowExceptionIfExecutingOnNoPage() { - try { - executeScript("return 1;"); - } catch (WebDriverException e) { - // Expected - return; - } - fail("Expected exception to be thrown"); + Throwable t = catchThrowable(() -> executeScript("return 1;")); + assertThat(t, instanceOf(WebDriverException.class)); } @JavascriptEnabled @@ -559,14 +546,8 @@ public void testShouldThrowAnExceptionWhenArgumentsWithStaleElementPassed() { } }; - try { - executeScript("return undefined;", args); - fail("Expected an exception"); - } catch (StaleElementReferenceException e) { - // This is expected - } catch (Exception ex) { - fail("Expected an StaleElementReferenceException exception, got " + ex); - } + Throwable t = catchThrowable(() -> executeScript("return undefined;", args)); + assertThat(t, instanceOf(StaleElementReferenceException.class)); } @JavascriptEnabled diff --git a/java/client/test/org/openqa/selenium/FormHandlingTest.java b/java/client/test/org/openqa/selenium/FormHandlingTest.java index 3ebcbe9259ac6..37e5cf38ddb06 100644 --- a/java/client/test/org/openqa/selenium/FormHandlingTest.java +++ b/java/client/test/org/openqa/selenium/FormHandlingTest.java @@ -19,11 +19,11 @@ 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.junit.Assert.fail; import static org.junit.Assume.assumeFalse; import static org.openqa.selenium.support.ui.ExpectedConditions.titleIs; import static org.openqa.selenium.testing.Driver.HTMLUNIT; @@ -31,6 +31,7 @@ import static org.openqa.selenium.testing.Driver.MARIONETTE; import static org.openqa.selenium.testing.Driver.PHANTOMJS; 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; @@ -56,12 +57,7 @@ public void testShouldClickOnSubmitInputElements() { @Test public void testClickingOnUnclickableElementsDoesNothing() { driver.get(pages.formPage); - try { - driver.findElement(By.xpath("//body")).click(); - } catch (Exception e) { - e.printStackTrace(); - fail("Clicking on the unclickable should be a no-op"); - } + driver.findElement(By.xpath("//body")).click(); } @Test @@ -93,13 +89,15 @@ public void testShouldSubmitAFormWhenAnyElementWithinThatFormIsSubmitted() { wait.until(titleIs("We Arrive Here")); } - @Test(expected = NoSuchElementException.class) + @Test @Ignore(value = {PHANTOMJS, SAFARI}) @NotYetImplemented( value = MARIONETTE, reason = "Delegates to JS and so the wrong exception is returned") public void testShouldNotBeAbleToSubmitAFormThatDoesNotExist() { driver.get(pages.formPage); - driver.findElement(By.name("SearchableText")).submit(); + WebElement element = driver.findElement(By.name("SearchableText")); + Throwable t = catchThrowable(element::submit); + assertThat(t, instanceOf(NoSuchElementException.class)); } @Test diff --git a/java/client/test/org/openqa/selenium/FrameSwitchingTest.java b/java/client/test/org/openqa/selenium/FrameSwitchingTest.java index 43e0f6522929b..9060bb1410186 100644 --- a/java/client/test/org/openqa/selenium/FrameSwitchingTest.java +++ b/java/client/test/org/openqa/selenium/FrameSwitchingTest.java @@ -19,11 +19,11 @@ 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.junit.Assert.fail; 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,10 +35,10 @@ import static org.openqa.selenium.testing.Driver.MARIONETTE; import static org.openqa.selenium.testing.Driver.PHANTOMJS; import static org.openqa.selenium.testing.Driver.SAFARI; +import static org.openqa.selenium.testing.TestUtilities.catchThrowable; import org.junit.After; import org.junit.Test; -import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.testing.Ignore; import org.openqa.selenium.testing.JUnit4TestBase; import org.openqa.selenium.testing.JavascriptEnabled; @@ -177,12 +177,8 @@ public void testShouldEnsureElementIsAFrameBeforeSwitching() { driver.get(pages.framesetPage); WebElement frame = driver.findElement(By.tagName("frameset")); - try { - driver.switchTo().frame(frame); - fail(); - } catch (NoSuchFrameException expected) { - // Do nothing. - } + Throwable t = catchThrowable(() -> driver.switchTo().frame(frame)); + assertThat(t, instanceOf(NoSuchFrameException.class)); } @Test @@ -192,22 +188,14 @@ public void testFrameSearchesShouldBeRelativeToTheCurrentlySelectedFrame() { driver.switchTo().frame("second"); assertThat(driver.findElement(By.id("pageNumber")).getText(), equalTo("2")); - try { - driver.switchTo().frame("third"); - fail(); - } catch (NoSuchFrameException expected) { - // Do nothing - } + Throwable t = catchThrowable(() -> driver.switchTo().frame("third")); + assertThat(t, instanceOf(NoSuchFrameException.class)); driver.switchTo().defaultContent(); driver.switchTo().frame("third"); - try { - driver.switchTo().frame("second"); - fail(); - } catch (NoSuchFrameException expected) { - // Do nothing - } + Throwable t2 = catchThrowable(() -> driver.switchTo().frame("second")); + assertThat(t2, instanceOf(NoSuchFrameException.class)); driver.switchTo().defaultContent(); driver.switchTo().frame("second"); @@ -227,37 +215,24 @@ public void testShouldThrowFrameNotFoundExceptionLookingUpSubFramesWithSuperFram driver.get(pages.framesetPage); driver.switchTo().frame("fourth"); - try { - driver.switchTo().frame("second"); - fail("Expected NoSuchFrameException"); - } catch (NoSuchFrameException e) { - // Expected - } - + Throwable t = catchThrowable(() -> driver.switchTo().frame("second")); + assertThat(t, instanceOf(NoSuchFrameException.class)); } @Test public void testShouldThrowAnExceptionWhenAFrameCannotBeFound() { driver.get(pages.xhtmlTestPage); - try { - driver.switchTo().frame("Nothing here"); - fail("Should not have been able to switch"); - } catch (NoSuchFrameException e) { - // This is expected - } + Throwable t = catchThrowable(() -> driver.switchTo().frame("Nothing here")); + assertThat(t, instanceOf(NoSuchFrameException.class)); } @Test public void testShouldThrowAnExceptionWhenAFrameCannotBeFoundByIndex() { driver.get(pages.xhtmlTestPage); - try { - driver.switchTo().frame(27); - fail("Should not have been able to switch"); - } catch (NoSuchFrameException e) { - // This is expected - } + Throwable t = catchThrowable(() -> driver.switchTo().frame(27)); + assertThat(t, instanceOf(NoSuchFrameException.class)); } @Ignore(value = {IE, PHANTOMJS, SAFARI}) @@ -338,12 +313,8 @@ public void testShouldAllowAUserToSwitchFromAnIframeBackToTheMainContentOfThePag driver.get(pages.iframePage); driver.switchTo().frame(0); - try { - driver.switchTo().defaultContent(); - driver.findElement(By.id("iframe_page_heading")); - } catch (Exception e) { - fail("Should have switched back to main content"); - } + driver.switchTo().defaultContent(); + driver.findElement(By.id("iframe_page_heading")); } @Test @@ -452,11 +423,7 @@ public void testShouldBeAbleToSwitchToTheTopIfTheFrameIsDeletedFromUnderUs() { driver.switchTo().frame("iframe1"); - try { - wait.until(presenceOfElementLocated(By.id("success"))); - } catch (WebDriverException web) { - fail("Could not find element after switching frame"); - } + wait.until(presenceOfElementLocated(By.id("success"))); } @Ignore(value = {PHANTOMJS}) @@ -465,7 +432,7 @@ public void testShouldBeAbleToSwitchToTheTopIfTheFrameIsDeletedFromUnderUs() { public void testShouldBeAbleToSwitchToTheTopIfTheFrameIsDeletedFromUnderUsWithFrameIndex() { driver.get(appServer.whereIs("frame_switching_tests/deletingFrame.html")); int iframe = 0; - wait.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(iframe)); + wait.until(frameToBeAvailableAndSwitchToIt(iframe)); // we should be in the frame now WebElement killIframe = driver.findElement(By.id("killIframe")); killIframe.click(); @@ -474,13 +441,9 @@ public void testShouldBeAbleToSwitchToTheTopIfTheFrameIsDeletedFromUnderUsWithFr WebElement addIFrame = driver.findElement(By.id("addBackFrame")); addIFrame.click(); - wait.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(iframe)); + wait.until(frameToBeAvailableAndSwitchToIt(iframe)); - try { - wait.until(presenceOfElementLocated(By.id("success"))); - } catch (WebDriverException web) { - fail("Could not find element after switching frame"); - } + wait.until(presenceOfElementLocated(By.id("success"))); } @Ignore(value = {PHANTOMJS}) @@ -489,7 +452,7 @@ public void testShouldBeAbleToSwitchToTheTopIfTheFrameIsDeletedFromUnderUsWithFr public void testShouldBeAbleToSwitchToTheTopIfTheFrameIsDeletedFromUnderUsWithWebelement() { driver.get(appServer.whereIs("frame_switching_tests/deletingFrame.html")); WebElement iframe = driver.findElement(By.id("iframe1")); - wait.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(iframe)); + wait.until(frameToBeAvailableAndSwitchToIt(iframe)); // we should be in the frame now WebElement killIframe = driver.findElement(By.id("killIframe")); killIframe.click(); @@ -500,13 +463,8 @@ public void testShouldBeAbleToSwitchToTheTopIfTheFrameIsDeletedFromUnderUsWithWe addIFrame.click(); iframe = driver.findElement(By.id("iframe1")); - wait.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(iframe)); - - try { - wait.until(presenceOfElementLocated(By.id("success"))); - } catch (WebDriverException web) { - fail("Could not find element after switching frame"); - } + wait.until(frameToBeAvailableAndSwitchToIt(iframe)); + wait.until(presenceOfElementLocated(By.id("success"))); } @Ignore(value = {CHROME, HTMLUNIT, IE, MARIONETTE, PHANTOMJS, SAFARI}, reason = "not tested") @@ -520,11 +478,8 @@ public void testShouldNotBeAbleToDoAnythingTheFrameIsDeletedFromUnderUs() { WebElement killIframe = driver.findElement(By.id("killIframe")); killIframe.click(); - try { - driver.findElement(By.id("killIframe")).click(); - fail("NoSuchFrameException should be thrown"); - } catch (NoSuchFrameException expected) { - } + Throwable t = catchThrowable(() -> driver.findElement(By.id("killIframe"))); + assertThat(t, instanceOf(NoSuchFrameException.class)); } @Test @@ -580,25 +535,11 @@ public void testGetShouldSwitchToDefaultContext() { && "44".compareTo(((HasCapabilities) driver).getCapabilities().getVersion()) <= 0); driver.get(pages.iframePage); - try { - driver.findElement(By.id("iframe1")); - } catch (NoSuchElementException e) { - fail("Expected to be on iframes.html, but " + e.getMessage()); - } - driver.switchTo().frame(driver.findElement(By.id("iframe1"))); - try { - driver.findElement(By.id("cheese")); // Found on formPage.html but not on iframes.html. - } catch (NoSuchElementException e) { - fail("Expected to be on formPage.html, but " + e.getMessage()); - } + driver.findElement(By.id("cheese")); // Found on formPage.html but not on iframes.html. driver.get(pages.iframePage); // This must effectively switchTo().defaultContent(), too. - try { - driver.findElement(By.id("iframe1")); - } catch (NoSuchElementException e) { - fail("Expected to be on iframes.html, but " + e.getMessage()); - } + driver.findElement(By.id("iframe1")); } private void assertFrameNotPresent(String locator) { diff --git a/java/client/test/org/openqa/selenium/ImplicitWaitTest.java b/java/client/test/org/openqa/selenium/ImplicitWaitTest.java index 440ff1a98919e..b18ada70d3404 100644 --- a/java/client/test/org/openqa/selenium/ImplicitWaitTest.java +++ b/java/client/test/org/openqa/selenium/ImplicitWaitTest.java @@ -19,13 +19,15 @@ 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.junit.Assert.fail; import static org.openqa.selenium.testing.Driver.IE; import static org.openqa.selenium.testing.Driver.MARIONETTE; import static org.openqa.selenium.testing.Driver.PHANTOMJS; import static org.openqa.selenium.testing.Driver.SAFARI; +import static org.openqa.selenium.testing.TestUtilities.catchThrowable; import org.junit.After; import org.junit.Before; @@ -71,11 +73,8 @@ public void testShouldImplicitlyWaitForASingleElement() { public void testShouldStillFailToFindAnElementWhenImplicitWaitsAreEnabled() { driver.get(pages.dynamicPage); driver.manage().timeouts().implicitlyWait(500, MILLISECONDS); - try { - driver.findElement(By.id("box0")); - fail("Expected to throw."); - } catch (NoSuchElementException expected) { - } + Throwable t = catchThrowable(() -> driver.findElement(By.id("box0"))); + assertThat(t, instanceOf(NoSuchElementException.class)); } @Test @@ -84,11 +83,8 @@ public void testShouldReturnAfterFirstAttemptToFindOneAfterDisablingImplicitWait driver.get(pages.dynamicPage); driver.manage().timeouts().implicitlyWait(3000, MILLISECONDS); driver.manage().timeouts().implicitlyWait(0, MILLISECONDS); - try { - driver.findElement(By.id("box0")); - fail("Expected to throw."); - } catch (NoSuchElementException expected) { - } + Throwable t = catchThrowable(() -> driver.findElement(By.id("box0"))); + assertThat(t, instanceOf(NoSuchElementException.class)); } @Test @@ -149,13 +145,7 @@ public void testShouldImplicitlyWaitForAnElementToBeVisibleBeforeInteracting() { assertFalse("revealed should not be visible", revealed.isDisplayed()); reveal.click(); - - try { - revealed.sendKeys("hello world"); - // This is what we want - } catch (ElementNotVisibleException e) { - fail("Element should have been visible"); - } + revealed.sendKeys("hello world"); } @@ -168,7 +158,7 @@ public void testShouldRetainImplicitlyWaitFromTheReturnedWebDriverOfFrameSwitchT driver.findElement(By.name("windowOne")).click(); Wait wait = new WebDriverWait(driver, 1); - wait.until(ExpectedConditions.numberOfwindowsToBe(2)); + wait.until(ExpectedConditions.numberOfWindowsToBe(2)); String handle = (String)driver.getWindowHandles().toArray()[1]; WebDriver newWindow = driver.switchTo().window(handle); diff --git a/java/client/test/org/openqa/selenium/KeysTest.java b/java/client/test/org/openqa/selenium/KeysTest.java index f33ec872ea040..229d9c24da2e6 100644 --- a/java/client/test/org/openqa/selenium/KeysTest.java +++ b/java/client/test/org/openqa/selenium/KeysTest.java @@ -22,7 +22,7 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertThat; -import static org.junit.Assert.fail; +import static org.openqa.selenium.testing.TestUtilities.catchThrowable; import org.junit.Test; import org.junit.runner.RunWith; @@ -53,12 +53,8 @@ public void validSubSequence() { @Test public void invalidSubSequenceThrows() { - try { - Keys.LEFT.subSequence(-1, 10); - fail("Expected IndexOutOfBoundsException"); - } catch (RuntimeException e) { - assertThat(e, is(instanceOf(IndexOutOfBoundsException.class))); - } + Throwable t = catchThrowable(() -> Keys.LEFT.subSequence(-1, 10)); + assertThat(t, instanceOf(IndexOutOfBoundsException.class)); } @Test diff --git a/java/client/test/org/openqa/selenium/ProxySettingTest.java b/java/client/test/org/openqa/selenium/ProxySettingTest.java index 8b3b94ca94c6c..b14b8ee3e5f05 100644 --- a/java/client/test/org/openqa/selenium/ProxySettingTest.java +++ b/java/client/test/org/openqa/selenium/ProxySettingTest.java @@ -202,22 +202,16 @@ public void requiredProxyCapabilityShouldHavePriority() { } private void registerDriverTeardown(final WebDriver driver) { - tearDowns.add(new Callable() { - @Override - public Object call() { - driver.quit(); - return null; - } + tearDowns.add(() -> { + driver.quit(); + return null; }); } private void registerProxyTeardown(final ProxyServer proxy) { - tearDowns.add(new Callable() { - @Override - public Object call() { - proxy.destroy(); - return null; - } + tearDowns.add(() -> { + proxy.destroy(); + return null; }); } @@ -258,16 +252,13 @@ private Server createServer(Handler handler) { server.setHandler(handler); - tearDowns.add(new Callable() { - @Override - public Object call() { - try { - server.stop(); - } catch (Exception e) { - throw new RuntimeException(e); - } - return null; + tearDowns.add(() -> { + try { + server.stop(); + } catch (Exception e) { + throw new RuntimeException(e); } + return null; }); try { diff --git a/java/client/test/org/openqa/selenium/ProxyTest.java b/java/client/test/org/openqa/selenium/ProxyTest.java index 7471cd23a5dde..85255e88ab911 100644 --- a/java/client/test/org/openqa/selenium/ProxyTest.java +++ b/java/client/test/org/openqa/selenium/ProxyTest.java @@ -18,16 +18,14 @@ 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.junit.Assert.fail; import static org.openqa.selenium.remote.CapabilityType.PROXY; - -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import java.util.Set; +import static org.openqa.selenium.testing.TestUtilities.catchThrowable; import org.junit.Ignore; import org.junit.Test; @@ -35,7 +33,6 @@ import org.junit.runners.JUnit4; import org.openqa.selenium.Proxy.ProxyType; import org.openqa.selenium.remote.BeanToJsonConverter; -import org.openqa.selenium.remote.CapabilityType; import org.openqa.selenium.remote.DesiredCapabilities; import org.openqa.selenium.remote.JsonToBeanConverter; @@ -64,88 +61,44 @@ public void testNotInitializedProxy() { @Test public void testCanNotChangeAlreadyInitializedProxyType() { - Proxy proxy = new Proxy(); + final Proxy proxy = new Proxy(); proxy.setProxyType(ProxyType.DIRECT); - try { - proxy.setAutodetect(true); - fail("Didn't throw expected assertion"); - } catch (IllegalStateException e) { - // Success - expected. - } - - try { - proxy.setSocksPassword(""); - fail("Didn't throw expected assertion"); - } catch (IllegalStateException e) { - // Success - expected. - } - - try { - proxy.setSocksUsername(""); - fail("Didn't throw expected assertion"); - } catch (IllegalStateException e) { - // Success - expected. - } - - try { - proxy.setSocksProxy(""); - fail("Didn't throw expected assertion"); - } catch (IllegalStateException e) { - // Success - expected. - } - - try { - proxy.setFtpProxy(""); - fail("Didn't throw expected assertion"); - } catch (IllegalStateException e) { - // Success - expected. - } - - try { - proxy.setHttpProxy(""); - fail("Didn't throw expected assertion"); - } catch (IllegalStateException e) { - // Success - expected. - } - - try { - proxy.setNoProxy(""); - fail("Didn't throw expected assertion"); - } catch (IllegalStateException e) { - // Success - expected. - } - - try { - proxy.setProxyAutoconfigUrl(""); - fail("Didn't throw expected assertion"); - } catch (IllegalStateException e) { - // Success - expected. - } - - try { - proxy.setProxyType(ProxyType.SYSTEM); - fail("Didn't throw expected assertion"); - } catch (IllegalStateException e) { - // Success - expected. - } - - try { - proxy.setSslProxy(""); - fail("Didn't throw expected assertion"); - } catch (IllegalStateException e) { - // Success - expected. - } - - proxy = new Proxy(); - proxy.setProxyType(ProxyType.AUTODETECT); + Throwable t = catchThrowable(() -> proxy.setAutodetect(true)); + assertThat(t, instanceOf(IllegalStateException.class)); + + Throwable t2 = catchThrowable(() -> proxy.setSocksPassword("")); + assertThat(t2, instanceOf(IllegalStateException.class)); + + Throwable t3 = catchThrowable(() -> proxy.setSocksUsername("")); + assertThat(t3, instanceOf(IllegalStateException.class)); + + Throwable t4 = catchThrowable(() -> proxy.setSocksProxy("")); + assertThat(t4, instanceOf(IllegalStateException.class)); + + Throwable t5 = catchThrowable(() -> proxy.setFtpProxy("")); + assertThat(t5, instanceOf(IllegalStateException.class)); + + Throwable t6 = catchThrowable(() -> proxy.setHttpProxy("")); + assertThat(t6, instanceOf(IllegalStateException.class)); + + Throwable t7 = catchThrowable(() -> proxy.setNoProxy("")); + assertThat(t7, instanceOf(IllegalStateException.class)); + + Throwable t8 = catchThrowable(() -> proxy.setProxyAutoconfigUrl("")); + assertThat(t8, instanceOf(IllegalStateException.class)); + + Throwable t9 = catchThrowable(() -> proxy.setProxyType(ProxyType.SYSTEM)); + assertThat(t9, instanceOf(IllegalStateException.class)); + + Throwable t10 = catchThrowable(() -> proxy.setSslProxy("")); + assertThat(t10, instanceOf(IllegalStateException.class)); + + final Proxy proxy2 = new Proxy(); + proxy2.setProxyType(ProxyType.AUTODETECT); - try { - proxy.setProxyType(ProxyType.SYSTEM); - fail("Didn't throw expected assertion"); - } catch (IllegalStateException e) { - // Success - expected. - } + Throwable t11 = catchThrowable(() -> proxy2.setProxyType(ProxyType.SYSTEM)); + assertThat(t11, instanceOf(IllegalStateException.class)); } @Test diff --git a/java/client/test/org/openqa/selenium/ReferrerTest.java b/java/client/test/org/openqa/selenium/ReferrerTest.java index fdc6d437bcade..ff4c280dcd262 100644 --- a/java/client/test/org/openqa/selenium/ReferrerTest.java +++ b/java/client/test/org/openqa/selenium/ReferrerTest.java @@ -38,8 +38,6 @@ import com.google.common.net.HostAndPort; import com.google.common.net.HttpHeaders; -import com.sun.corba.se.impl.orbutil.HexOutputStream; - import org.junit.BeforeClass; import org.junit.Rule; import org.junit.Test; @@ -61,7 +59,6 @@ import java.io.IOException; import java.io.UnsupportedEncodingException; -import java.net.URI; import java.net.URL; import java.net.URLEncoder; import java.nio.file.Files; diff --git a/java/client/test/org/openqa/selenium/SessionHandlingTest.java b/java/client/test/org/openqa/selenium/SessionHandlingTest.java index 89243a89fee66..e6e075ce43c00 100644 --- a/java/client/test/org/openqa/selenium/SessionHandlingTest.java +++ b/java/client/test/org/openqa/selenium/SessionHandlingTest.java @@ -17,11 +17,14 @@ package org.openqa.selenium; +import static org.hamcrest.Matchers.instanceOf; +import static org.junit.Assert.assertThat; import static org.openqa.selenium.testing.Driver.FIREFOX; import static org.openqa.selenium.testing.Driver.MARIONETTE; import static org.openqa.selenium.testing.Driver.PHANTOMJS; import static org.openqa.selenium.testing.Driver.REMOTE; import static org.openqa.selenium.testing.Driver.SAFARI; +import static org.openqa.selenium.testing.TestUtilities.catchThrowable; import org.junit.Test; import org.junit.runner.RunWith; @@ -38,13 +41,7 @@ public void callingQuitMoreThanOnceOnASessionIsANoOp() { WebDriver driver = new WebDriverBuilder().get(); driver.quit(); - - try { - driver.quit(); - } catch (RuntimeException e) { - throw new RuntimeException( - "It should be possible to quit a session more than once, got exception:", e); - } + driver.quit(); } @Test @@ -53,24 +50,19 @@ public void callingQuitAfterClosingTheLastWindowIsANoOp() { WebDriver driver = new WebDriverBuilder().get(); driver.close(); - - try { - driver.quit(); - } catch (RuntimeException e) { - throw new RuntimeException( - "It should be possible to quit a session more than once, got exception:", e); - } + driver.quit(); } - @Test(expected = NoSuchSessionException.class) + @Test @Ignore(value = {SAFARI}, reason = "Safari: throws UnreachableBrowserException") public void callingAnyOperationAfterQuitShouldThrowAnException() { WebDriver driver = new WebDriverBuilder().get(); driver.quit(); - driver.getCurrentUrl(); + Throwable t = catchThrowable(driver::getCurrentUrl); + assertThat(t, instanceOf(NoSuchSessionException.class)); } - @Test(expected = NoSuchSessionException.class) + @Test @Ignore(value = {FIREFOX, PHANTOMJS, SAFARI, MARIONETTE}, reason = "Firefox: can perform an operation after closing the last window," + "PhantomJS: throws NoSuchWindowException," @@ -78,7 +70,8 @@ public void callingAnyOperationAfterQuitShouldThrowAnException() { public void callingAnyOperationAfterClosingTheLastWindowShouldThrowAnException() { WebDriver driver = new WebDriverBuilder().get(); driver.close(); - driver.getCurrentUrl(); + Throwable t = catchThrowable(driver::getCurrentUrl); + assertThat(t, instanceOf(NoSuchSessionException.class)); } } diff --git a/java/client/test/org/openqa/selenium/StaleElementReferenceTest.java b/java/client/test/org/openqa/selenium/StaleElementReferenceTest.java index 26b171a0cd228..015d5877769c8 100644 --- a/java/client/test/org/openqa/selenium/StaleElementReferenceTest.java +++ b/java/client/test/org/openqa/selenium/StaleElementReferenceTest.java @@ -17,9 +17,11 @@ 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.junit.Assert.fail; 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; @@ -32,12 +34,8 @@ public void testOldPage() { driver.get(pages.simpleTestPage); WebElement elem = driver.findElement(By.id("links")); driver.get(pages.xhtmlTestPage); - try { - elem.click(); - fail(); - } catch (StaleElementReferenceException e) { - // do nothing. this is what we expected. - } + Throwable t = catchThrowable(elem::click); + assertThat(t, instanceOf(StaleElementReferenceException.class)); } @JavascriptEnabled @@ -46,12 +44,8 @@ public void testShouldNotCrashWhenCallingGetSizeOnAnObsoleteElement() { driver.get(pages.simpleTestPage); WebElement elem = driver.findElement(By.id("links")); driver.get(pages.xhtmlTestPage); - try { - elem.getSize(); - fail(); - } catch (StaleElementReferenceException e) { - // do nothing. this is what we expected. - } + Throwable t = catchThrowable(elem::getSize); + assertThat(t, instanceOf(StaleElementReferenceException.class)); } @JavascriptEnabled @@ -60,12 +54,8 @@ public void testShouldNotCrashWhenQueryingTheAttributeOfAStaleElement() { driver.get(pages.xhtmlTestPage); WebElement heading = driver.findElement(By.xpath("//h1")); driver.get(pages.simpleTestPage); - try { - heading.getAttribute("class"); - fail(); - } catch (StaleElementReferenceException e) { - // do nothing. this is what we expected. - } + Throwable t = catchThrowable(() -> heading.getAttribute("class")); + assertThat(t, instanceOf(StaleElementReferenceException.class)); } @JavascriptEnabled diff --git a/java/client/test/org/openqa/selenium/TextPagesTest.java b/java/client/test/org/openqa/selenium/TextPagesTest.java index 9e99f4fc2dd5b..d30482c97b2c7 100644 --- a/java/client/test/org/openqa/selenium/TextPagesTest.java +++ b/java/client/test/org/openqa/selenium/TextPagesTest.java @@ -17,13 +17,15 @@ package org.openqa.selenium; +import static org.hamcrest.Matchers.instanceOf; import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; +import static org.junit.Assert.assertThat; 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.PHANTOMJS; import static org.openqa.selenium.testing.Driver.SAFARI; +import static org.openqa.selenium.testing.TestUtilities.catchThrowable; import org.junit.Before; import org.junit.Test; @@ -54,12 +56,8 @@ public void testShouldBeAbleToLoadASimplePageOfText() { public void testFindingAnElementOnAPlainTextPageWillNeverWork() { driver.get(textPage); - try { - driver.findElement(By.id("foo")); - fail("This shouldn't work"); - } catch (NoSuchElementException e) { - // this is expected - } + Throwable t = catchThrowable(() -> driver.findElement(By.id("foo"))); + assertThat(t, instanceOf(NoSuchElementException.class)); } @Ignore(value = {CHROME, IE, SAFARI, PHANTOMJS}, @@ -69,11 +67,7 @@ public void testShouldThrowExceptionWhenAddingCookieToAPageThatIsNotHtml() { driver.get(textPage); Cookie cookie = new Cookie.Builder("hello", "goodbye").build(); - try { - driver.manage().addCookie(cookie); - fail("Should throw exception when adding cookie to non existing domain"); - } catch (WebDriverException e) { - // This is expected - } + Throwable t = catchThrowable(() -> driver.manage().addCookie(cookie)); + assertThat(t, instanceOf(WebDriverException.class)); } } diff --git a/java/client/test/org/openqa/selenium/UnexpectedAlertBehaviorTest.java b/java/client/test/org/openqa/selenium/UnexpectedAlertBehaviorTest.java index 94f0764eae3ee..ae2b2e3e14bba 100644 --- a/java/client/test/org/openqa/selenium/UnexpectedAlertBehaviorTest.java +++ b/java/client/test/org/openqa/selenium/UnexpectedAlertBehaviorTest.java @@ -17,7 +17,8 @@ package org.openqa.selenium; -import static org.junit.Assert.fail; +import static org.hamcrest.Matchers.instanceOf; +import static org.junit.Assert.assertThat; import static org.junit.Assume.assumeTrue; import static org.openqa.selenium.WaitingConditions.elementTextToEqual; import static org.openqa.selenium.remote.CapabilityType.UNEXPECTED_ALERT_BEHAVIOUR; @@ -27,6 +28,7 @@ import static org.openqa.selenium.testing.Driver.MARIONETTE; import static org.openqa.selenium.testing.Driver.PHANTOMJS; import static org.openqa.selenium.testing.Driver.SAFARI; +import static org.openqa.selenium.testing.TestUtilities.catchThrowable; import org.junit.After; import org.junit.Test; @@ -76,12 +78,9 @@ public void dismissUnhandledAlertsByDefault() { @NotYetImplemented(HTMLUNIT) @Test public void canIgnoreUnhandledAlert() { - try { - runScenarioWithUnhandledAlert(UnexpectedAlertBehaviour.IGNORE, "Text ignored"); - fail("Exception not thrown"); - } catch (UnhandledAlertException ex) { - // this is expected - } + Throwable t = catchThrowable( + () -> runScenarioWithUnhandledAlert(UnexpectedAlertBehaviour.IGNORE, "Text ignored")); + assertThat(t, instanceOf(UnhandledAlertException.class)); driver2.switchTo().alert().dismiss(); } diff --git a/java/client/test/org/openqa/selenium/VisibilityTest.java b/java/client/test/org/openqa/selenium/VisibilityTest.java index 178afd64fe6e0..9ca8acd865ee5 100644 --- a/java/client/test/org/openqa/selenium/VisibilityTest.java +++ b/java/client/test/org/openqa/selenium/VisibilityTest.java @@ -17,13 +17,13 @@ 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.junit.Assert.fail; import static org.junit.Assume.assumeFalse; import static org.openqa.selenium.Platform.ANDROID; import static org.openqa.selenium.support.ui.ExpectedConditions.not; @@ -33,6 +33,7 @@ import static org.openqa.selenium.testing.Driver.MARIONETTE; import static org.openqa.selenium.testing.Driver.PHANTOMJS; 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; @@ -107,12 +108,8 @@ public void testShouldNotBeAbleToClickOnAnElementThatIsNotDisplayed() { driver.get(pages.javascriptPage); WebElement element = driver.findElement(By.id("unclickable")); - try { - element.click(); - fail("You should not be able to click on an invisible element"); - } catch (ElementNotInteractableException e) { - // This is expected - } + Throwable t = catchThrowable(element::click); + assertThat(t, instanceOf(ElementNotInteractableException.class)); } @Test @@ -121,13 +118,8 @@ public void testShouldNotBeAbleToTypeToAnElementThatIsNotDisplayed() { driver.get(pages.javascriptPage); WebElement element = driver.findElement(By.id("unclickable")); - try { - element.sendKeys("You don't see me"); - fail("You should not be able to send keyboard input to an invisible element"); - } catch (ElementNotInteractableException e) { - // This is expected - } - + 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"))); } diff --git a/java/client/test/org/openqa/selenium/WindowSwitchingTest.java b/java/client/test/org/openqa/selenium/WindowSwitchingTest.java index 3c3891f4f671b..b09066b0ae5c7 100644 --- a/java/client/test/org/openqa/selenium/WindowSwitchingTest.java +++ b/java/client/test/org/openqa/selenium/WindowSwitchingTest.java @@ -18,11 +18,11 @@ 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.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertThat; -import static org.junit.Assert.fail; import static org.junit.Assume.assumeFalse; import static org.openqa.selenium.Platform.ANDROID; import static org.openqa.selenium.WaitingConditions.newWindowIsOpened; @@ -32,6 +32,7 @@ import static org.openqa.selenium.testing.Driver.IE; import static org.openqa.selenium.testing.Driver.MARIONETTE; import static org.openqa.selenium.testing.Driver.REMOTE; +import static org.openqa.selenium.testing.TestUtilities.catchThrowable; import com.google.common.collect.Sets; @@ -85,13 +86,11 @@ public void testShouldThrowNoSuchWindowException() { String current = driver.getWindowHandle(); try { - driver.switchTo().window("invalid name"); - fail("NoSuchWindowException expected"); - } catch (NoSuchWindowException e) { - // Expected. + Throwable t = catchThrowable(() -> driver.switchTo().window("invalid name")); + assertThat(t, instanceOf(NoSuchWindowException.class)); + } finally { + driver.switchTo().window(current); } - - driver.switchTo().window(current); } @NoDriverAfterTest(failedOnly = true) @@ -110,10 +109,8 @@ public void testShouldThrowNoSuchWindowExceptionOnAnAttemptToGetItsHandle() { driver.close(); try { - driver.getWindowHandle(); - fail("NoSuchWindowException expected"); - } catch (NoSuchWindowException e) { - // Expected. + Throwable t = catchThrowable(driver::getWindowHandle); + assertThat(t, instanceOf(NoSuchWindowException.class)); } finally { driver.switchTo().window(current); } @@ -135,19 +132,11 @@ public void testShouldThrowNoSuchWindowExceptionOnAnyOperationIfAWindowIsClosed( driver.close(); try { - try { - driver.getTitle(); - fail("NoSuchWindowException expected"); - } catch (NoSuchWindowException e) { - // Expected. - } + Throwable t = catchThrowable(driver::getTitle); + assertThat(t, instanceOf(NoSuchWindowException.class)); - try { - driver.findElement(By.tagName("body")); - fail("NoSuchWindowException expected"); - } catch (NoSuchWindowException e) { - // Expected. - } + Throwable t2 = catchThrowable(() -> driver.findElement(By.tagName("body"))); + assertThat(t2, instanceOf(NoSuchWindowException.class)); } finally { driver.switchTo().window(current); } @@ -170,10 +159,8 @@ public void testShouldThrowNoSuchWindowExceptionOnAnyElementOperationIfAWindowIs driver.close(); try { - body.getText(); - fail("NoSuchWindowException expected"); - } catch (NoSuchWindowException e) { - // Expected. + Throwable t = catchThrowable(body::getText); + assertThat(t, instanceOf(NoSuchWindowException.class)); } finally { driver.switchTo().window(current); } @@ -299,15 +286,10 @@ public void testFailingToSwitchToAWindowLeavesTheCurrentWindowAsIs() { driver.get(pages.xhtmlTestPage); String current = driver.getWindowHandle(); - try { - driver.switchTo().window("i will never exist"); - fail("Should not be ablt to change to a non-existant window"); - } catch (NoSuchWindowException e) { - // expected - } + Throwable t = catchThrowable(() -> driver.switchTo().window("i will never exist")); + assertThat(t, instanceOf(NoSuchWindowException.class)); String newHandle = driver.getWindowHandle(); - assertEquals(current, newHandle); } diff --git a/java/client/test/org/openqa/selenium/testing/TestUtilities.java b/java/client/test/org/openqa/selenium/testing/TestUtilities.java index beb0f4624b1f7..42adf492f3797 100644 --- a/java/client/test/org/openqa/selenium/testing/TestUtilities.java +++ b/java/client/test/org/openqa/selenium/testing/TestUtilities.java @@ -26,6 +26,7 @@ import org.openqa.selenium.remote.CapabilityType; import org.openqa.selenium.testing.drivers.SauceDriver; +import java.util.function.Consumer; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -198,4 +199,13 @@ public static Platform getEffectivePlatform(WebDriver driver) { public static boolean isLocal() { return !Boolean.getBoolean("selenium.browser.remote") && !SauceDriver.shouldUseSauce(); } + + public static Throwable catchThrowable(Runnable f) { + try { + f.run(); + } catch (Throwable throwable) { + return throwable; + } + return null; + } }