Selenium C# Tutorial: ExpectedException Attribute explained

Updated: Jan 18

While working with unit tests, it is widespread that our tests will fail due to one exception or another, and these types of exceptions are commonly known exceptions. We want to bypass these exceptions to mark the test as 'Pass.' For fulfilling this practice, we can use the ExpectedException Attribute, which allows us to bypass the known exceptions.

Let's write a test case that searches for an element that does not exist and fail with "NoSuchElementException"

[TestMethod]
public void NoSuchElementError()
{
tmpElement = driver.FindElement(By.Id("Element is not Exists"));            
}

Result:

Now rewrite our test method with the ExpectedException Attribute and again run the test.

[TestMethod]
[ExpectedException(typeof(NoSuchElementException))]
public void NoSuchElementException()        
{
tmpElement = driver.FindElement(By.Id("Element is not Exists"));            
}

Result:




22 views0 comments