Selenium 2 - checking error messages - selenium

I want to check error messages. These error messages appear only when my website encounters a problem.
My problem is that I use findElement in order to check the error message. So when something goes wrong, Selenium finds it, and everything is O.K.
But when it doesn't (meaning - my website is O.K with no problems) - then Selenium indicates that it doesn't find the element, and rises an exception.
Any idea?

you can surround the findElement in a try-catch block, which will do nothing if the element is not found. e.g.
private boolean isElementPresent(By by) {
try {
driver.findElement(by);
return true;
} catch (NoSuchElementException e) {
return false;
//or do nothing
}
}

Take a look at the answer Selenium Webdriver NoSuchElementException
It suggests the following (I've adapted it a bit for your needs) :
List<WebElement> errorElements = driver.findElements(By.id("ERROR_ID"));
if (!errorElements.empty()) {
// Tests your errors
}

1.For this you should design your test case in such a way that you writes code to check error message only when you are sure that you will get error message.
2.But the point is why are you checking for error message when you know that there will be no problem and code will run fine.
3.If you doesn't know that error will occur.. You can place the risky code in try block and write a catch block which will find error message and check it.

Related

If selenium can't find an element do something

I'm using maven and selenium for testing in java. I would like to know if there is a way to call a function every time a test fails. I already have a function that takes an screenshot of the browser. I would like to use it every time selenium throws NoSuchElNoSuchElementExeption for example.
Is there an "easy" way to implement this?
Thank you!
You can create a method to find the element and implement a try-catch block inside that to catch the NoSuchElementException. Call your function to take the screenshot inside that catch block.
e.g.
public WebElement findElement(By locator) {
try {
WebElement element = driver.findElement(locator);
return element;
} catch (NoSuchElementException nse) {
// call the function to take a screenshot
}
}
I eventually found this solution to the problem:
https://darrellgrainger.blogspot.com/2011/02/generating-screen-capture-on-exception.html?m=1
Consists on using WebDriverEventListener.

What is the correct Selenium syntax to assert that I'm unable to view a particular link/element?

I have a Selenium test that is supposed to verify that I'm unable to see a button link unless there is a certain amount of information present on a page such as a pagination link for example. Here is my Selenium assert statement:
def test_bottom_links
load_page('orgs/apache_software')
$driver.find_element(:xpath => "//a[#id='btn_orgs_see_all_projects']").element? == false
end
In my mind this makes sense to me but I receive this error when I run my test:
Selenium::WebDriver::Error::NoSuchElementError: Unable to locate element: {"method":"xpath","selector":"//a[#id='btn_orgs_see_all_projects']"}
The above error is what I want as a passing statement. I don't want Selenium to find this element because it should not be there.
I've also tried this and I get the same error:
$driver.find_element(:xpath => "//a[#id='btn_orgs_see_all_projects']").displayed? == false
I was wondering what the correct syntax should be to make this test pass. I've referred to these linksassertNotSomething and List of Selenium Methods. However, these don't have examples of how they are used so I was wondering how someone would write a test like the above. Thanks for any help offered.
Here's a simple boolean check method that should work.
boolean checkForElementPresence(By locator)
{
try {
driver.findElement(locator);
return true;
} catch (NoSuchElementException e) {
return false;
}
}
You can switch to $driver.find_elements that will return an array without raising an exception. Then you can check for the size of the array to make sure it is empty indicating that the element was not found.

How to catch 500 server error with selenium webdriver during a test in a webpage?

i have a java code with selenium webdriver to test the presence of some element in a webpage.
The test passed each time it found elements but sometime when i have a 500 server error message on the top of the webpage, the test passes successfully.
How can i fetch this server error message in my test.
What is the web element of this error message?
Any help
Thank you
I've done a check similar to this before in a Regression suite...
One thing you can do, is have a function that gets executed very frequently. Something like this:
(your tags are vague, so i will use pseudo-Java / WebDriver with jUnit)
import static org.junit.Assert.fail;
public void check500() {
if (isPresent(driver.findElement(By.cssSelector("div#500.error"))))
fail("500 page displayed! Failing test, and quitting.");
}
You will, of course, replace "div#500.error" with whatever element that IS unique within the 500 error page. There's always going to be one. Look around.
I do this to catch my errors present on a webpage
try {
List<WebElement> errors = m_driver
.findElements(By.className(ALERT));
//Print all the error messages displayed
for (WebElement e : errors)
log("MESSAGE : " + e.getText());
}
catch (Exception e) {
}
You can replace the By.className by anything else you want.

Handling Windows Store App exceptions from GetFileAsync

I have a problem with the following code example:
Windows::Storage::StorageFolder^ location = Package::Current->InstalledLocation;
try
{
task<StorageFile^> GetFileTask(location->GetFileAsync(sn));
GetFileTask.then([=](StorageFile^ file)
{
try
{
task<IBuffer^> ReadFileTask(FileIO::ReadBufferAsync(file));
ReadFileTask.then([=](IBuffer^ readBuffer)
{
// process file contents here
});
}
catch(Platform::Exception^ ex)
{
// Handle error here
}
});
}
catch(Platform::Exception^ ex)
{
// Handle error here
}
When using a filename that doesn't exist the function throws an exception:
Unhandled exception at 0x0FFCC531 (msvcr110d.dll) in GameTest2.exe: An invalid parameter was passed to a function that considers invalid parameters fatal.
I've been searching the internet and this exception breaks only when connected to the debugger. I'm using VS 2012. I've turned off all the relevant 'break on exception' but it still causes the debugger to break and non of my handlers are getting a chance to handle the exception.
If the file is missing I would expect the GetFileAsync method to throw a 'File doesn't exist' exception. Not sure why it keeps throwing the 'Invalid parameter' exception.
This is starting to bother me and I just can't find any known solution to this issue. Anyone have any ideas?
I'm going to try and change the method to not use the task<> code. Instead I'll call the GetFileAsync using 'await'. However I believe 'await' will just cause the calling thread to wait until the GetFileAsync has finished, which kind of defeats the point of asynchronous loading.
I'm wondering if this is a common issue with exception handling when using tasks.
Update:
OK, I've now found the solution:
task<StorageFile^>( location->GetFileAsync(sn)).then([](StorageFile^ openedFile)
{
return FileIO::ReadBufferAsync(openedFile);
}).then([](IBuffer^ readBuffer)
{
// Process file
}).then([](task<void> t)
{
try
{
t.get();
}
catch(Platform::Exception^ e)
{
// Handle error
}
});
It seems there needs to be an extra 'then' condition added to the end of the chain to pick up the exception.

Throw an exception or Assert.Fail if prerequisite to tests are not met

I have a few NUnit tests that run Selenium.
There are some prerequisite to some tests. An example for this would be logging in to our website.
We use a standard test user for test A, but if that user doesn't exist for whatever reason, we'll get a test failure with nothing useful (Selenium will just report it couldn't find the element at line 50). So I planned to check for the user's existence before we try to run the test - in the TextFixtureSetUp method.
I have a check to ensure the user exists, and if not, throw a helpful error message.
For example:
[TestFixtureSetUp]
public void SetUp()
{
bool userExists = userManager.GetUserByEmailAddress("someuser#fish.com") != null;
if (!userExists)
{
throw new Exception("Test user someuser#fish.com doesn't exist.");
}
}
vs
[TestFixtureSetUp]
public void SetUp()
{
bool userExists = userManager.GetUserByEmailAddress("someuser#fish.com") != null;
if (!userExists)
{
Assert.Fail("Test user someuser#fish.com doesn't exist.");
}
}
My question is this a good idea? Should I throw an exception or use Assert.Fail()? Am I thinking about this in the wrong way, or is it something doesn't matter really.
Reason to throw exception - you can catch it later on and try to use another user.
Reason to fail asserrt - when user is not found, it means end to the testmodel.
If you go the exception way - think about GetUserByEmailAddress will be throwing it if it does not find the right user...
Instead of Assert.Fail() raising AssertionException, I would rather use Assert.Inconclusive() or better Assume.That(userManager.GetUserByEmailAddress("someuser#fish.com"), Is.Not.Null) to raise InconclusiveException in this case.
You may want to watch it here: https://docs.nunit.org/articles/nunit/writing-tests/Assumptions.html