Skip to content

Commit 794820d

Browse files
committed
use the right AssertJ method assertThatThrownBy instead of error-prone construct "try/fail/catch(expected)".
1 parent a855017 commit 794820d

29 files changed

+466
-722
lines changed

java/src/org/openqa/selenium/grid/sessionmap/jdbc/JdbcBackedSessionMap.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -221,7 +221,7 @@ public Session get(SessionId id) throws NoSuchSessionException {
221221
try (ResultSet sessions = statement.executeQuery()) {
222222
if (!sessions.next()) {
223223
NoSuchSessionException exception =
224-
new NoSuchSessionException("Unable to find session.");
224+
new NoSuchSessionException("Unable to find session with id: " + id);
225225
span.setAttribute("error", true);
226226
span.setStatus(Status.NOT_FOUND);
227227
EXCEPTION.accept(attributeMap, exception);

java/src/org/openqa/selenium/grid/sessionmap/redis/RedisBackedSessionMap.java

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -223,7 +223,8 @@ public URI getUri(SessionId id) throws NoSuchSessionException {
223223
attributeMap.put(REDIS_URI_KEY, uriKey);
224224

225225
if (rawUri == null) {
226-
NoSuchSessionException exception = new NoSuchSessionException("Unable to find session.");
226+
NoSuchSessionException exception =
227+
new NoSuchSessionException("Unable to find session with id: " + id);
227228
span.setAttribute("error", true);
228229
span.setStatus(Status.NOT_FOUND);
229230
EXCEPTION.accept(attributeMap, exception);

java/test/org/openqa/selenium/CorrectEventFiringTest.java

Lines changed: 7 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -17,9 +17,7 @@
1717

1818
package org.openqa.selenium;
1919

20-
import static org.assertj.core.api.Assertions.assertThat;
21-
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
22-
import static org.junit.jupiter.api.Assertions.fail;
20+
import static org.assertj.core.api.Assertions.*;
2321
import static org.junit.jupiter.api.Assumptions.assumeFalse;
2422
import static org.openqa.selenium.WaitingConditions.elementTextToContain;
2523
import static org.openqa.selenium.WaitingConditions.elementTextToEqual;
@@ -180,11 +178,9 @@ public void testShouldFireMouseMoveEventWhenClicking() {
180178
void testShouldNotThrowIfEventHandlerThrows() {
181179
driver.get(pages.javascriptPage);
182180

183-
try {
184-
driver.findElement(By.id("throwing-mouseover")).click();
185-
} catch (WebDriverException e) {
186-
fail("Error in event handler should not have propagated: " + e);
187-
}
181+
assertThatCode(() -> driver.findElement(By.id("throwing-mouseover")).click())
182+
.as("Error in event handler should not have propagated")
183+
.doesNotThrowAnyException();
188184
}
189185

190186
@Test
@@ -410,9 +406,9 @@ public void testSendingKeysToAFocusedElementShouldNotBlurThatElement() {
410406
throw new RuntimeException(e);
411407
}
412408
}
413-
if (!focused) {
414-
fail("Clicking on element didn't focus it in time - can't proceed so failing");
415-
}
409+
assertThat(focused)
410+
.as("If clicking on element didn't focus it in time, we can't proceed with the test")
411+
.isTrue();
416412

417413
element.sendKeys("a");
418414
assertEventNotFired("blur", driver);

java/test/org/openqa/selenium/PageLoadTimeOutTest.java

Lines changed: 27 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -17,14 +17,13 @@
1717

1818
package org.openqa.selenium;
1919

20+
import static java.lang.System.currentTimeMillis;
2021
import static org.assertj.core.api.Assertions.assertThat;
21-
import static org.junit.jupiter.api.Assertions.fail;
22+
import static org.assertj.core.api.Assertions.assertThatThrownBy;
2223
import static org.openqa.selenium.WaitingConditions.elementTextToEqual;
2324
import static org.openqa.selenium.support.ui.ExpectedConditions.titleIs;
2425
import static org.openqa.selenium.support.ui.ExpectedConditions.visibilityOfElementLocated;
25-
import static org.openqa.selenium.testing.drivers.Browser.CHROME;
26-
import static org.openqa.selenium.testing.drivers.Browser.EDGE;
27-
import static org.openqa.selenium.testing.drivers.Browser.SAFARI;
26+
import static org.openqa.selenium.testing.drivers.Browser.*;
2827

2928
import java.time.Duration;
3029
import org.junit.jupiter.api.Test;
@@ -72,22 +71,16 @@ void testShouldTimeoutIfAPageTakesTooLongToLoad() {
7271
@Ignore(value = SAFARI, reason = "Flaky")
7372
public void testShouldTimeoutIfAPageTakesTooLongToLoadAfterClick() {
7473
driver.manage().timeouts().pageLoadTimeout(Duration.ofSeconds(2));
75-
76-
driver.get(appServer.whereIs("page_with_link_to_slow_loading_page.html"));
77-
WebElement link = wait.until(visibilityOfElementLocated(By.id("link-to-slow-loading-page")));
78-
79-
long start = System.currentTimeMillis();
8074
try {
81-
link.click();
82-
fail("I should have timed out");
83-
} catch (RuntimeException e) {
84-
long end = System.currentTimeMillis();
75+
driver.get(appServer.whereIs("page_with_link_to_slow_loading_page.html"));
76+
WebElement link = wait.until(visibilityOfElementLocated(By.id("link-to-slow-loading-page")));
8577

86-
assertThat(e).isInstanceOf(TimeoutException.class);
78+
long start = currentTimeMillis();
8779

88-
int duration = (int) (end - start);
89-
assertThat(duration).isGreaterThan(2000);
90-
assertThat(duration).isLessThan(5000);
80+
assertThatThrownBy(() -> link.click()).isInstanceOf(TimeoutException.class);
81+
82+
long duration = currentTimeMillis() - start;
83+
assertThat(duration).isBetween(2000L, 5000L);
9184
} finally {
9285
driver.manage().timeouts().pageLoadTimeout(Duration.ofSeconds(300));
9386
}
@@ -109,18 +102,13 @@ public void testShouldTimeoutIfAPageTakesTooLongToRefresh() {
109102

110103
driver.manage().timeouts().pageLoadTimeout(Duration.ofSeconds(2));
111104

112-
long start = System.currentTimeMillis();
113105
try {
114-
driver.navigate().refresh();
115-
fail("I should have timed out");
116-
} catch (RuntimeException e) {
117-
long end = System.currentTimeMillis();
106+
long start = currentTimeMillis();
118107

119-
assertThat(e).isInstanceOf(TimeoutException.class);
108+
assertThatThrownBy(() -> driver.navigate().refresh()).isInstanceOf(TimeoutException.class);
120109

121-
int duration = (int) (end - start);
122-
assertThat(duration).isGreaterThanOrEqualTo(2000);
123-
assertThat(duration).isLessThan(4000);
110+
long duration = currentTimeMillis() - start;
111+
assertThat(duration).isBetween(2000L, 4000L);
124112
} finally {
125113
driver.manage().timeouts().pageLoadTimeout(Duration.ofSeconds(300));
126114
}
@@ -163,19 +151,18 @@ private void testPageLoadTimeoutIsEnforced(long webDriverPageLoadTimeout) {
163151

164152
private void assertPageLoadTimeoutIsEnforced(
165153
long webDriverPageLoadTimeout, long pageLoadTimeBuffer) {
166-
long start = System.currentTimeMillis();
167-
try {
168-
driver.get(
169-
appServer.whereIs("sleep?time=" + (webDriverPageLoadTimeout + pageLoadTimeBuffer)));
170-
fail("I should have timed out after " + webDriverPageLoadTimeout + " seconds");
171-
} catch (RuntimeException e) {
172-
long end = System.currentTimeMillis();
173-
174-
assertThat(e).isInstanceOf(TimeoutException.class);
175-
176-
long duration = end - start;
177-
assertThat(duration).isGreaterThanOrEqualTo(webDriverPageLoadTimeout * 1000);
178-
assertThat(duration).isLessThan((webDriverPageLoadTimeout + pageLoadTimeBuffer) * 1000);
179-
}
154+
long start = currentTimeMillis();
155+
assertThatThrownBy(
156+
() -> {
157+
driver.get(
158+
appServer.whereIs(
159+
"sleep?time=" + (webDriverPageLoadTimeout + pageLoadTimeBuffer)));
160+
})
161+
.as("Should have timed out after " + webDriverPageLoadTimeout + " seconds")
162+
.isInstanceOf(TimeoutException.class);
163+
164+
long duration = currentTimeMillis() - start;
165+
assertThat(duration).isGreaterThanOrEqualTo(webDriverPageLoadTimeout * 1000);
166+
assertThat(duration).isLessThan((webDriverPageLoadTimeout + pageLoadTimeBuffer) * 1000);
180167
}
181168
}

java/test/org/openqa/selenium/TakesScreenshotTest.java

Lines changed: 30 additions & 56 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,6 @@
1818
package org.openqa.selenium;
1919

2020
import static org.assertj.core.api.Assertions.assertThat;
21-
import static org.junit.jupiter.api.Assertions.fail;
2221
import static org.junit.jupiter.api.Assumptions.assumeTrue;
2322
import static org.openqa.selenium.support.ui.ExpectedConditions.frameToBeAvailableAndSwitchToIt;
2423
import static org.openqa.selenium.support.ui.ExpectedConditions.titleIs;
@@ -108,7 +107,7 @@ void testGetScreenshotAsBinary() {
108107

109108
@Test
110109
@Ignore(value = CHROME, gitHubActions = true)
111-
public void testShouldCaptureScreenshotOfCurrentViewport() {
110+
public void testShouldCaptureScreenshotOfCurrentViewport() throws IOException {
112111
driver.get(appServer.whereIs("screen/screen.html"));
113112

114113
BufferedImage screenshot = getImage();
@@ -147,7 +146,7 @@ void testShouldCaptureScreenshotOfAnElement() throws Exception {
147146

148147
@Test
149148
@Ignore(value = CHROME, gitHubActions = true)
150-
public void testShouldCaptureScreenshotAtFramePage() {
149+
public void testShouldCaptureScreenshotAtFramePage() throws IOException {
151150
driver.get(appServer.whereIs("screen/screen_frames.html"));
152151
wait.until(frameToBeAvailableAndSwitchToIt(By.id("frame1")));
153152
wait.until(visibilityOfAllElementsLocatedBy(By.id("content")));
@@ -184,7 +183,7 @@ public void testShouldCaptureScreenshotAtFramePage() {
184183
@Test
185184
@Ignore(CHROME)
186185
@Ignore(EDGE)
187-
public void testShouldCaptureScreenshotAtIFramePage() {
186+
public void testShouldCaptureScreenshotAtIFramePage() throws IOException {
188187
driver.get(appServer.whereIs("screen/screen_iframes.html"));
189188

190189
BufferedImage screenshot = getImage();
@@ -214,7 +213,7 @@ public void testShouldCaptureScreenshotAtIFramePage() {
214213
@Test
215214
@Ignore(FIREFOX)
216215
@Ignore(value = CHROME, gitHubActions = true)
217-
public void testShouldCaptureScreenshotAtFramePageAfterSwitching() {
216+
public void testShouldCaptureScreenshotAtFramePageAfterSwitching() throws IOException {
218217
driver.get(appServer.whereIs("screen/screen_frames.html"));
219218

220219
driver.switchTo().frame(driver.findElement(By.id("frame2")));
@@ -248,7 +247,7 @@ public void testShouldCaptureScreenshotAtFramePageAfterSwitching() {
248247
@Ignore(CHROME)
249248
@Ignore(EDGE)
250249
@Ignore(FIREFOX)
251-
public void testShouldCaptureScreenshotAtIFramePageAfterSwitching() {
250+
public void testShouldCaptureScreenshotAtIFramePageAfterSwitching() throws IOException {
252251
driver.get(appServer.whereIs("screen/screen_iframes.html"));
253252

254253
driver.switchTo().frame(driver.findElement(By.id("iframe2")));
@@ -272,7 +271,7 @@ public void testShouldCaptureScreenshotAtIFramePageAfterSwitching() {
272271
/* grid X size */ 6,
273272
/* grid Y size */ 6));
274273

275-
// expectation is that screenshot at page with Iframes after switching to a Iframe
274+
// expectation is that screenshot at page with Iframes after switching to iframe
276275
// will be taken for full page
277276
compareColors(expectedColors, actualColors);
278277
}
@@ -282,17 +281,12 @@ public void testShouldCaptureScreenshotAtIFramePageAfterSwitching() {
282281
*
283282
* @return Image object
284283
*/
285-
private BufferedImage getImage() {
286-
BufferedImage image = null;
287-
try {
288-
byte[] imageData = screenshooter.getScreenshotAs(OutputType.BYTES);
289-
assertThat(imageData).isNotNull();
290-
assertThat(imageData.length).isPositive();
291-
image = ImageIO.read(new ByteArrayInputStream(imageData));
292-
assertThat(image).isNotNull();
293-
} catch (IOException e) {
294-
fail("Image screenshot file is invalid: " + e.getMessage());
295-
}
284+
private BufferedImage getImage() throws IOException {
285+
byte[] imageData = screenshooter.getScreenshotAs(OutputType.BYTES);
286+
assertThat(imageData).isNotNull();
287+
assertThat(imageData.length).isPositive();
288+
BufferedImage image = ImageIO.read(new ByteArrayInputStream(imageData));
289+
assertThat(image).isNotNull();
296290

297291
// saveImageToTmpFile(image);
298292
return image;
@@ -337,28 +331,23 @@ private Set<String> generateExpectedColors(
337331
private Set<String> scanActualColors(BufferedImage image, final int stepX, final int stepY) {
338332
Set<String> colors = new TreeSet<>();
339333

340-
try {
341-
int height = image.getHeight();
342-
int width = image.getWidth();
343-
assertThat(width > 0).isTrue();
344-
assertThat(height > 0).isTrue();
345-
346-
Raster raster = image.getRaster();
347-
for (int i = 0; i < width; i = i + stepX) {
348-
for (int j = 0; j < height; j = j + stepY) {
349-
String hex =
350-
String.format(
351-
"#%02x%02x%02x",
352-
(raster.getSample(i, j, 0)),
353-
(raster.getSample(i, j, 1)),
354-
(raster.getSample(i, j, 2)));
355-
colors.add(hex);
356-
}
334+
int height = image.getHeight();
335+
int width = image.getWidth();
336+
assertThat(width > 0).isTrue();
337+
assertThat(height > 0).isTrue();
338+
339+
Raster raster = image.getRaster();
340+
for (int i = 0; i < width; i = i + stepX) {
341+
for (int j = 0; j < height; j = j + stepY) {
342+
String hex =
343+
String.format(
344+
"#%02x%02x%02x",
345+
(raster.getSample(i, j, 0)),
346+
(raster.getSample(i, j, 1)),
347+
(raster.getSample(i, j, 2)));
348+
colors.add(hex);
357349
}
358-
} catch (Exception e) {
359-
fail("Unable to get actual colors from screenshot: " + e.getMessage());
360350
}
361-
362351
assertThat(colors).isNotEmpty();
363352

364353
return colors;
@@ -379,17 +368,7 @@ private void compareColors(Set<String> expectedColors, Set<String> actualColors)
379368
cleanActualColors.remove("#000000");
380369
cleanActualColors.remove("#ffffff");
381370

382-
if (!expectedColors.containsAll(cleanActualColors)) {
383-
fail(
384-
"There are unexpected colors on the screenshot: "
385-
+ Sets.difference(cleanActualColors, expectedColors));
386-
}
387-
388-
if (!cleanActualColors.containsAll(expectedColors)) {
389-
fail(
390-
"There are expected colors not present on the screenshot: "
391-
+ Sets.difference(expectedColors, cleanActualColors));
392-
}
371+
assertThat(cleanActualColors).containsExactlyInAnyOrderElementsOf(expectedColors);
393372
}
394373

395374
private boolean onlyBlack(Set<String> colors) {
@@ -406,13 +385,8 @@ private boolean onlyWhite(Set<String> colors) {
406385
* @param im image
407386
*/
408387
@SuppressWarnings("unused")
409-
private void saveImageToTmpFile(String testMethodName, BufferedImage im) {
410-
388+
private void saveImageToTmpFile(String testMethodName, BufferedImage im) throws IOException {
411389
File outputfile = new File(testMethodName + "_image.png");
412-
try {
413-
ImageIO.write(im, "png", outputfile);
414-
} catch (IOException e) {
415-
fail("Unable to write image to file: " + e.getMessage());
416-
}
390+
ImageIO.write(im, "png", outputfile);
417391
}
418392
}

java/test/org/openqa/selenium/WebScriptTest.java

Lines changed: 9 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -18,8 +18,7 @@
1818
package org.openqa.selenium;
1919

2020
import static java.util.concurrent.TimeUnit.SECONDS;
21-
import static org.assertj.core.api.Assertions.assertThat;
22-
import static org.assertj.core.api.Assertions.fail;
21+
import static org.assertj.core.api.Assertions.*;
2322
import static org.openqa.selenium.support.ui.ExpectedConditions.visibilityOf;
2423

2524
import java.time.Duration;
@@ -90,12 +89,10 @@ void canRemoveConsoleMessageHandler()
9089
ConsoleLogEntry logEntry = future1.get(5, TimeUnit.SECONDS);
9190
assertThat(logEntry.getText()).isEqualTo("Hello, world!");
9291

93-
try {
94-
future2.get(5, TimeUnit.SECONDS);
95-
fail("Should be able to read the console messages");
96-
} catch (TimeoutException e) {
97-
assertThat(e).isNotNull();
98-
}
92+
assertThatThrownBy(() -> future2.get(5, TimeUnit.SECONDS))
93+
.as("Should be able to read the console messages")
94+
.isInstanceOf(TimeoutException.class);
95+
9996
((RemoteWebDriver) driver).script().removeConsoleMessageHandler(id1);
10097
}
10198

@@ -144,12 +141,9 @@ void canRemoveJsErrorHandler() throws ExecutionException, InterruptedException,
144141
assertThat(logEntry.getType()).isEqualTo("javascript");
145142
assertThat(logEntry.getLevel()).isEqualTo(LogLevel.ERROR);
146143

147-
try {
148-
future2.get(5, TimeUnit.SECONDS);
149-
fail("Should be able to read the JS errors");
150-
} catch (TimeoutException e) {
151-
assertThat(e).isNotNull();
152-
}
144+
assertThatThrownBy(() -> future2.get(5, TimeUnit.SECONDS))
145+
.as("Should be able to read the JS errors")
146+
.isInstanceOf(TimeoutException.class);
153147

154148
((RemoteWebDriver) driver).script().removeConsoleMessageHandler(id1);
155149
}
@@ -259,7 +253,7 @@ void canPinScript() throws ExecutionException, InterruptedException, TimeoutExce
259253

260254
@Test
261255
@NeedsFreshDriver
262-
void canUnpinScript() throws ExecutionException, InterruptedException, TimeoutException {
256+
void canUnpinScript() {
263257
CountDownLatch latch = new CountDownLatch(2);
264258

265259
String pinnedScript =

0 commit comments

Comments
 (0)