Skip to content

Commit 0954cca

Browse files
[dotnet] Modernize exception handling in tests via assert that throws (#14776)
1 parent 60e3171 commit 0954cca

File tree

10 files changed

+248
-240
lines changed

10 files changed

+248
-240
lines changed

dotnet/src/webdriver/WebDriver.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -935,7 +935,7 @@ private static object ConvertObjectToJavaScriptObject(object arg)
935935
}
936936
else
937937
{
938-
throw new ArgumentException("Argument is of an illegal type" + arg.ToString(), nameof(arg));
938+
throw new ArgumentException("Argument is of an illegal type: " + arg.ToString(), nameof(arg));
939939
}
940940

941941
return converted;

dotnet/test/common/AlertsTest.cs

Lines changed: 43 additions & 52 deletions
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,9 @@ public void ShouldThrowArgumentNullExceptionWhenKeysNull()
6060
IAlert alert = WaitFor<IAlert>(AlertToBePresent, "No alert found");
6161
try
6262
{
63-
Assert.That(() => alert.SendKeys(null), Throws.ArgumentNullException);
63+
Assert.That(
64+
() => alert.SendKeys(null),
65+
Throws.ArgumentNullException);
6466
}
6567
finally
6668
{
@@ -147,13 +149,12 @@ public void SettingTheValueOfAnAlertThrows()
147149
driver.FindElement(By.Id("alert")).Click();
148150

149151
IAlert alert = WaitFor<IAlert>(AlertToBePresent, "No alert found");
152+
150153
try
151154
{
152-
alert.SendKeys("cheese");
153-
Assert.Fail("Expected exception");
154-
}
155-
catch (ElementNotInteractableException)
156-
{
155+
Assert.That(
156+
() => alert.SendKeys("cheese"),
157+
Throws.TypeOf<ElementNotInteractableException>());
157158
}
158159
finally
159160
{
@@ -198,8 +199,10 @@ public void AlertShouldNotAllowAdditionalCommandsIfDismissed()
198199

199200
IAlert alert = WaitFor<IAlert>(AlertToBePresent, "No alert found");
200201
alert.Dismiss();
201-
string text;
202-
Assert.That(() => text = alert.Text, Throws.InstanceOf<NoAlertPresentException>());
202+
203+
Assert.That(
204+
() => alert.Text,
205+
Throws.TypeOf<NoAlertPresentException>());
203206
}
204207

205208
[Test]
@@ -249,7 +252,9 @@ public void SwitchingToMissingAlertThrows()
249252
{
250253
driver.Url = CreateAlertPage("cheese");
251254

252-
Assert.That(() => AlertToBePresent(), Throws.InstanceOf<NoAlertPresentException>());
255+
Assert.That(
256+
() => AlertToBePresent(),
257+
Throws.TypeOf<NoAlertPresentException>());
253258
}
254259

255260
[Test]
@@ -270,15 +275,9 @@ public void SwitchingToMissingAlertInAClosedWindowThrows()
270275
driver.Close();
271276
WaitFor(WindowHandleCountToBe(1), "Window count was not 1");
272277

273-
try
274-
{
275-
AlertToBePresent().Accept();
276-
Assert.Fail("Expected exception");
277-
}
278-
catch (NoSuchWindowException)
279-
{
280-
// Expected
281-
}
278+
Assert.That(
279+
() => AlertToBePresent().Accept(),
280+
Throws.TypeOf<NoSuchWindowException>());
282281

283282
}
284283
finally
@@ -321,17 +320,22 @@ public void HandlesTwoAlertsFromOneInteraction()
321320
{
322321
driver.Url = EnvironmentManager.Instance.UrlBuilder.CreateInlinePage(new InlinePage()
323322
.WithScripts(
324-
"function setInnerText(id, value) {",
325-
" document.getElementById(id).innerHTML = '<p>' + value + '</p>';",
326-
"}",
327-
"function displayTwoPrompts() {",
328-
" setInnerText('text1', prompt('First'));",
329-
" setInnerText('text2', prompt('Second'));",
330-
"}")
323+
"""
324+
function setInnerText(id, value) {
325+
document.getElementById(id).innerHTML = '<p>' + value + '</p>';
326+
}
327+
328+
function displayTwoPrompts() {
329+
setInnerText('text1', prompt('First'));
330+
setInnerText('text2', prompt('Second'));
331+
}
332+
""")
331333
.WithBody(
332-
"<a href='#' id='double-prompt' onclick='displayTwoPrompts();'>click me</a>",
333-
"<div id='text1'></div>",
334-
"<div id='text2'></div>"));
334+
"""
335+
<a href='#' id='double-prompt' onclick='displayTwoPrompts();'>click me</a>
336+
<div id='text1'></div>
337+
<div id='text2'></div>
338+
"""));
335339

336340
driver.FindElement(By.Id("double-prompt")).Click();
337341

@@ -355,7 +359,7 @@ public void HandlesTwoAlertsFromOneInteraction()
355359
public void ShouldHandleAlertOnPageLoad()
356360
{
357361
string pageWithOnLoad = EnvironmentManager.Instance.UrlBuilder.CreateInlinePage(new InlinePage()
358-
.WithOnLoad("javascript:alert(\"onload\")")
362+
.WithOnLoad("""javascript:alert("onload")""")
359363
.WithBody("<p>Page with onload event handler</p>"));
360364
driver.Url = EnvironmentManager.Instance.UrlBuilder.CreateInlinePage(new InlinePage()
361365
.WithBody(string.Format("<a id='open-page-with-onload-alert' href='{0}'>open new page</a>", pageWithOnLoad)));
@@ -411,17 +415,12 @@ public void ShouldNotHandleAlertInAnotherWindow()
411415
Assert.AreEqual(1, allWindows.Count);
412416
onloadWindow = allWindows[0];
413417

414-
try
418+
Assert.That(() =>
415419
{
416420
IWebElement el = driver.FindElement(By.Id("open-new-window"));
417421
WaitFor<IAlert>(AlertToBePresent, TimeSpan.FromSeconds(5), "No alert found");
418-
Assert.Fail("Expected exception");
419-
}
420-
catch (WebDriverException)
421-
{
422-
// An operation timed out exception is expected,
423-
// since we're using WaitFor<T>.
424-
}
422+
},
423+
Throws.TypeOf<WebDriverException>());
425424

426425
}
427426
finally
@@ -442,15 +441,10 @@ public void IncludesAlertTextInUnhandledAlertException()
442441

443442
driver.FindElement(By.Id("alert")).Click();
444443
WaitFor<IAlert>(AlertToBePresent, "No alert found");
445-
try
446-
{
447-
string title = driver.Title;
448-
Assert.Fail("Expected UnhandledAlertException");
449-
}
450-
catch (UnhandledAlertException e)
451-
{
452-
Assert.AreEqual("cheese", e.AlertText);
453-
}
444+
445+
Assert.That(
446+
() => driver.Title,
447+
Throws.TypeOf<UnhandledAlertException>().With.Property(nameof(UnhandledAlertException.AlertText)).EqualTo("cheese"));
454448
}
455449

456450
[Test]
@@ -522,16 +516,14 @@ private Func<IWebElement> ElementToBePresent(By locator)
522516
{
523517
return () =>
524518
{
525-
IWebElement foundElement = null;
526519
try
527520
{
528-
foundElement = driver.FindElement(By.Id("open-page-with-onunload-alert"));
521+
return driver.FindElement(By.Id("open-page-with-onunload-alert"));
529522
}
530523
catch (NoSuchElementException)
531524
{
525+
return null;
532526
}
533-
534-
return foundElement;
535527
};
536528
}
537529

@@ -554,9 +546,8 @@ private Func<bool> WindowWithName(string name)
554546
}
555547
catch (NoSuchWindowException)
556548
{
549+
return false;
557550
}
558-
559-
return false;
560551
};
561552
}
562553

dotnet/test/common/CorrectEventFiringTest.cs

Lines changed: 4 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -348,20 +348,12 @@ public void SendingKeysToAFocusedElementShouldNotBlurThatElement()
348348
focused = true;
349349
break;
350350
}
351-
try
352-
{
353-
System.Threading.Thread.Sleep(200);
354-
}
355-
catch (Exception)
356-
{
357-
throw;
358-
}
359-
}
360-
if (!focused)
361-
{
362-
Assert.Fail("Clicking on element didn't focus it in time - can't proceed so failing");
351+
352+
System.Threading.Thread.Sleep(200);
363353
}
364354

355+
Assert.That(focused, Is.True, "Clicking on element didn't focus it in time - can't proceed so failing");
356+
365357
element.SendKeys("a");
366358
AssertEventNotFired("blur");
367359
}

dotnet/test/common/ElementAttributeTest.cs

Lines changed: 7 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -127,28 +127,19 @@ public void ShouldThrowExceptionIfSendingKeysToElementDisabledUsingRandomDisable
127127
{
128128
driver.Url = formsPage;
129129
IWebElement disabledTextElement1 = driver.FindElement(By.Id("disabledTextElement1"));
130-
try
130+
131+
Assert.That(() =>
131132
{
132133
disabledTextElement1.SendKeys("foo");
133-
Assert.Fail("Should have thrown exception");
134-
}
135-
catch (InvalidElementStateException)
136-
{
137-
//Expected
138-
}
134+
}, Throws.TypeOf<ElementNotInteractableException>());
139135

140136
Assert.AreEqual(string.Empty, disabledTextElement1.Text);
141137

142138
IWebElement disabledTextElement2 = driver.FindElement(By.Id("disabledTextElement2"));
143-
try
144-
{
145-
disabledTextElement2.SendKeys("bar");
146-
Assert.Fail("Should have thrown exception");
147-
}
148-
catch (InvalidElementStateException)
149-
{
150-
//Expected
151-
}
139+
140+
Assert.That(
141+
() => disabledTextElement2.SendKeys("bar"),
142+
Throws.TypeOf<ElementNotInteractableException>());
152143

153144
Assert.AreEqual(string.Empty, disabledTextElement2.Text);
154145
}

dotnet/test/common/Environment/RemoteSeleniumServer.cs

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -91,14 +91,15 @@ public async Task StopAsync()
9191
{
9292
if (autoStart && webserverProcess != null && !webserverProcess.HasExited)
9393
{
94-
using var httpClient = new HttpClient();
95-
96-
try
97-
{
98-
using var response = await httpClient.GetAsync("http://localhost:6000/selenium-server/driver?cmd=shutDownSeleniumServer");
99-
}
100-
catch (Exception ex) when (ex is HttpRequestException || ex is TimeoutException)
94+
using (var httpClient = new HttpClient())
10195
{
96+
try
97+
{
98+
using var response = await httpClient.GetAsync("http://localhost:6000/selenium-server/driver?cmd=shutDownSeleniumServer");
99+
}
100+
catch (Exception ex) when (ex is HttpRequestException || ex is TimeoutException)
101+
{
102+
}
102103
}
103104

104105
webserverProcess.WaitForExit(10000);

0 commit comments

Comments
 (0)