Fail Webdriver test if element is present - testing

I'm new to Webdriver and I'm wondering how do I make my test case fail if an element is present. Using the following code I can send an output that if the element id errorMessages is present an output will be displayed. Is there anyway I can make the test fail also?
if (driver.findElements(By.id("errorMessages")).size() != 0) {
System.out.println("Error..Warning Subscriber already exists ");
}

With TestNG you can simply use Assert.fail("your message"); inside the if block to mark the test as failed. Something like:
if (driver.findElements(By.id("errorMessages")).size() != 0) {
Assert.fail("Error..Warning Subscriber already exists ");
}
See this for overloading

I think you are looking at it in the wrong way. Rather than checking if the size is what you expect and then forcing the test to fail, use the inbuilt assertion methods so it reads much more like a logical statement:
assertTrue(driver.findElements(By.id("errorMessages")).size() == 0, "Error..Warning Subscriber already exists");
Documentation from the TestNG site
The inbuilt assertion methods will then print out that message if that assertion fails.

Related

E2E testing multiple posibilities with exception

i have a problem that i don't exactly know how to solve. I'm implementing an E2E test in which using selenium i need to click in a Link and check that is sending me to the right URL.
Here starts the problem...
There are 3 possibilities, mix of 2 types of links, just one type of link or the other type of link. No problems with the situations in which there are both types of links but when there is just one type when it searches for the identifier we use for the links that are not in page it gives me a timeoutException. This is not a failure because it's a posible situation but i will like to know if there is a way in which to check that if it finds no links it asserts that the exception is thrown.
I though using a runCatching (or try catch) wait for the link to appear and if it doesn't appear the test asserts that when i look for the element the timeout exception is thrown again.
It smells a bit for me this way of doing it and i don't know if it's correctly done.
EDIT: Im ussing AssertK and JUnit5 for testing.
EDIT 2: I've done this, i dont know if it a correct way of doing it
runCatching {
driver.waitFor(numberOfWidgetsToBeMoreThan(BrowserSelector.cssSelector(OFFERS_WITH_PRICE_AND_DATE), 0), ofMillis(2000))
}.onFailure {
assertThrows<WaitTimeoutException> {
findLink(OFFERS_WITH_PRICE_AND_DATE)
}
}.onSuccess {
val widget = findLink(OFFERS_WITH_PRICE_AND_DATE)
widget.click()
assertThat(driver.url).contains(NO_DATE_TEXT)
}
I'm not sure I understood your problem correctly, but you can use assertFails to assert that a piece of code throws an exception:
#Test
fun test() {
val exception = assertFails {
// some code that should throw
}
// some more assertions on the type of exception etc. may go here
}

SOAP UI - Set a node value in all test step's requests of all test cases in a test suites

I'm trying to set a node value in all test step's requests xml of all test cases in a test suite.
The groovy script is in the first test case and I get an error (XmlException: Unexpected Element: CDATA) as soon as the script try to edit the same tag in the second test case.
def groovyUtils = new com.eviware.soapui.support.GroovyUtils( context )
def AlltestCases = testRunner.testCase.testSuite.project.testSuites[testRunner.testCase.testSuite.name]
0.upto(AlltestCases.getTestCaseCount()) {
AlltestCases.getTestCaseList().each{
it.getTestStepList().each{ if(it.getClass()==com.eviware.soapui.impl.wsdl.teststeps.WsdlTestRequestStep){
if(it.getName().toLowerCase().contains("verify")){
step = groovyUtils.getXmlHolder("${it.getName()}"+"#Request")
step.setNodeValue("//*:Name/text()", "\$"+"{#TestSuite#NAME_ID}")
step.updateProperty()
}
}
}
}
}
If I understand your question correctly, you want to "inject" a value in a number of requests?
I would advise against that. I would rather set some project property, and then let each of the requests simply use that particular variable.
The most important reason for me to prefer this approach, is to make it more tranparent what is happening in your testcase, should someone else at some point - like if you get a different job - would need to take over your SoapUI projects. Currently you have requests, which hold values that appear to come out of nowhere. I would advise to make it clear that the request contains some sort of variable, and where that variable comes from.
Besides you will then also get more flexibility. If a few reqeusts at some point changes the path or name of the entity you want to change, you will need to make your code above handle that kind of situation. Not so, if you are merely using a variable in each of your requests.

#Test(enabled=false) is not shown as skipped test case

We have a number of TestNG tests that are disabled due to functionality not yet being present (enabled = false), but when the test classes are executed the disabled tests do not show up as skipped in the TestNG report. We'd like to know at the time of execution how many tests are disabled (i.e. skipped). At the moment we have to count the occurrences of enabled = false in the test classes which is an overhead.
Is there a different annotation to use or something else we are missing so that our test reports can display the number of disabled tests?
For example below method still gets executed : -
#Test(enabled=false)
public void ignoretestcase()
{
System.out.println("Ignore Test case");
}
you can use SkipException
throw new SkipException("Skip the test");
Check this post Skip TestNg test in runtime

Condition- assert using Selenium

I want to write a script which can detect this message " System is not responding to your request. Kindly try after sometime." as shown in the screenshot below. When this message comes up then I want verify and send mail to the development team.
Snippet which I wrote for verification purpose but it is not working fine for me, pls suggest some alternative:
String s1 = d1.findElementByXPath(".//*[#id='showSearchResultDiv']").getText();
System.out.println(s1);
Remember to be careful when writing code for automation. If the scenario doesn't always show up, you cannot try and find an XPath, because you can't getText() if the object (based on the XPath) doesn't exist first. You probably need a try/catch around your code, and then put the println inside the try. This scenario will occur quite frequently, so you may want to write your own framework on top of WebDriver to handle these use cases.
If that is not the issue. Put a try/catch around the code that is failing to capture what the exception is.
You should try to wait for your element to appear before examining its text:
for (int second = 0;; second++) {
if (second >= 60) fail("timeout");
try { if (d1.findElementByXPath(".//*[#id='showSearchResultDiv']").isDisplayed()) break; } catch (Exception e) {}
Thread.sleep(1000);
}
String s1 = d1.findElementByXPath(".//*[#id='showSearchResultDiv']").getText();
System.out.println(s1);
The exact code may be different, depending on the webpage you're testing (e.g. you should remove the 'fail' line if it's OK for the element not to appear every time.

Getting failure detail on failed scala/maven/specs tests

I am playing a bit with scala, using maven and scala plugin.
I can't find a way to have
mvn test
report failure details - in particular, whenever some function returns wrong reply, I am getting information about the failure, but I have no way to see WHICH wrong reply was reported.
For example, with test like:
object MyTestSpec extends Specification {
"my_function" should {
"return proper value for 3" {
val cnt = MyCode.my_function(3)
cnt must be_==(3)
}
}
}
in case my function returns something different than 3, I get only
Failed tests:
my_function should return proper value for 3
but there is no information what value was actually returned.
Is it possible to get this info somehow (apart from injecting manual println's)?
The Maven JUnit plugin only shows the failed tests in the console and not error messages. If you want to read the failure message you need to open the corresponding target/site/surefire-reports/MyTestSpecs.txt file.
You can also swap Maven for sbt-0.6.9 (Simple Build Tool) which can run specs specifications.
Eric.
cnt aka "my_function return value" must be_==(3)