TestNG try/catch not working properly - java

I am working on a test automation framework that someone previously built. The framework reads test data from an excel file and uses Selenium webdriver to control the browser and perform tests.
I am adding functionality to this framework by adding a TestNG class that reads data from a CSV file. Some functions in the current framework use try/catch. So when I call these functions from the TestNG class, TestNG will always say that the test passed, no matter what.
For example, this is from the current framework;
if (enterValueInBox.length() >= 1) {
try {
browserActions.typeValueInTextBox(myDriver, enterValueInBox);
} catch (Exception e) {
System.out.println("enterValueInBox failed");
}
}
This if statement is inside a function. It doesn't matter whether this functions works or not, it will always pass in TestNG. Even if Selenium can not find the element for example.
How can I work around this? Do I have to change the try/catch?
EDIT: Another example from the same function. The function basically consists of several if statements just like the two I am showing here. They all have the same signature, so an if statement with try/catch inside. Also worth mentioning, the function/class I am calling is not a TestNG class. So I built a TestNG class, and calling a non-TestNG class->method.
if (backSpaceInTextBox.length() > 1) {
try {
wa.handleSeleneseCommand(myDriver, Properties.TIME_TO_WAIT,
"niet gelukt");
browserActions.doBackSpaceInTextBox(myDriver,
backSpaceInTextBox);
} catch (Exception e) {
System.out.println("Could not do backspace");
}
}

Your tests are passing because test function completes
without any assertion failures
without exception thrown from test method
In your case, you should do one of
do not catch exceptions at all. Declare test methods to throw those exceptions
catch exception and fail test (Assert.fail)

Try this :
if (enterValueInBox.length() >= 1)
{
try
{
browserActions.typeValueInTextBox(myDriver, enterValueInBox);
}
catch (Exception e)
{
Assert.fail("EnterValueInBox failed", e);
}
}
Your test will fail when an Exception is thrown.

Related

Is it possible to add a variable where code should be?

I am currently trying to create an automation framework using Java and Selenium.
I want to create a line of code which essentially can read any input and make it a line of runnable code. For example, in an external file, a user could post 'id' into a field, that field will then be read by my program and execute the line. driver.findElement(By.id(.......)
Currently I'm using a bunch of if statements to do this for each identifier e.g. id, cssSelector, Xpath etc etc but then I'll need to do the same for the actions used by the program .click, .sendKeys etc so the program will just keep expanding and look overall very messy.
Is there a solution that would allow me to do this in a nicer way or am I stuck with my original approach?
Reflection is probably the most direct way to solve this. It essentially allows classes and methods to be looked up by their string names.
Here's a fag-packet example of how you might approach this using the snippet you provided, but I suggest you read some documentation before diving in.
Element findElementReflectively(Driver driver, String elementType, String thingToSearchFor) {
try {
Method m = By.class.getMethod(elementType, String.class);
if(!Modifier.isStatic(m.getModifiers())) {
throw new NoSuchMethodException("'By' method is not static.");
}
return driver.findElement(m.invoke(null, thingToSearchFor));
} catch (IllegalAccessException | NoSuchMethodException e) {
throw new IllegalArgumentException("Unknown element type: " + elementType, e);
} catch (InvocationTargetException e) {
throw new RuntimeException("Failed to find requested element.", e.getCause());
}
}
It depends on what you actually want to do.
Reading an id from a file and then execute code can be achieved through config file with this : Properties
Or if you want to execute full input code just search a little bit more
How to execute console or GUI input as if it was actual Java code?

Can we handle Assert fail in try and catch in testNG

I am trying to automate application using selenium webDriver + TestNG.
In which I am using multiple assert statement like
Assert.assertEquals("Dhaval", "Dhaval1");
and I am trying to catch the assertionfail exception using try& catch block.
as i am filling up an excell sheet for test result .
But any how while assertion fails application direct stop execution and catch block is will not execute.
Any suggestion.
Thanks in Advance!!!!
Catching exceptions on test assertions is a bad practice, they are asserts for a reason.
What you want to do is implement custom ITestListener and define required logic in onTestFailure(ITestResult result) method, code in this method will be executed if case will fail.
Try this:
try {
Assert.assertEquals("Dhaval", "Dhaval1");
}
catch (AssertionError e) {
Assert.assertEquals("Dhaval", "Dhaval");
}
If you are handling the tests results inside the test methods to save it to the spreadsheet, you are doing a bad practice. Take a look here to void this: http://www.techbeamers.com/save-selenium-webdriver-testng-result-excel/
Else, if you really need to do this:
try {
Assert.assertNotEquals(actualValue, expectedValue);
} catch (Exception e) {
// Thread the excpetion here
}

how to use assertion in selenium so that if it throws assertion error next line will not skip(java)

I am using assert to verify the scenario in Selenium webdriver.
Below is my code. If I get assertion error in my first line, the execution is not happening for next line. But I want to execute the next line as well and want to print the fail report in testng xslt. I am using ANT to trigger my build.
Assert.assertEquals(actualdatesent, expecteddatesent, "comparing assert date");
Assert.assertEquals(actualuccnumber, expecteduccnumber);
Edit
Try-catch block
try
{
Assert.assertEquals(actualdatesent, expecteddatesent, "date validation failed");
Assert.assertEquals(actualuccnumber, expecteduccnumber, number validation failed);
}
catch(Throwable T)
{
ErrorUtils.addVerificationFailure(T);
SeleniumScreenshot.takeFailedScreenshot(testname);
}
The only way is to surround every assert with try {} catch (AssertionError ex) and store the messages from exception in a list. At the end of method you will need to check if list is not empty and throw AssertionError yourself with all messages from list concatenated.

How to run one test against multiple sites using Selenium and TestNG

Given 3 web applications under test with given URLs:
www.A.com
www.B.com
www.C.com
How do I proceed to design a way using Selenium to run a single TestNG test against these three browsers and print out the results.
Current Strategy:
I have a java class with a main method, a properties file containing the the 3 urls listed above.
In this class i have a while loop that parses these properties file like below snippet, and for each url, programmatically calls an ant task that automates the build from compilation to test-run to result archiving. The problem is that after the first run completes, it doesn't return to the while loop to do it again. You might ask why i want to run it three times. The idea as already explained is to be able to run a suite of tests against multiple websites automatically and printout results without intervention. Code Snippet
try {
reader = new BufferedReader(new FileReader(new File(filename)));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
while((line=reader.readLine()) != null){
//call ant target to archive result
userprops.setProperty("url", line);
org.apache.tools.ant.Main.start(target, userprops, loader);
}
}catch (IOException e) {
e.printStackTrace();
}
I hope somebody understands what am trying to do and can help me understand why the while loop terminates after the first test run. Also maybe can offer another easier strategy with TestNG.
thanks Guys. Y.ou guys Rock!!
It seems to me that if you are using ANT you shouldn't need your class. I would just use three targets and assign the different properties within those targets.

Asserting in the example below

testLogicalDoc = new LogicalDocumentImpl(-4);
assertTrue(testLogicalDoc==null);
In my code above, I have an assert condition with which I want to make sure I don't create my object with negative size. It is a stringBuilder beneath the covers which throws NegativeArrayBoundsException for a size less than zero. But my junit test fails here. I don't know any other way of making sure an object is not created with a negative size.
Any thoughts on how this could be tested ? or should it be a Junit test at all ??
Many thanks,
-Pan
EDIT:
#Test(expected=NegativeArraySizeException.class)
public void testCreate4b()
{
LogicalDocumentImpl testLogicalDoc = new LogicalDocumentImpl(-4);
}
I'm catching the exception in the LogicalDocumentImpl class but still this test fails with an assertion error but only succeeds when I do a try catch on assertion error ..why is that so ??
if you are throwing NegativeArrayBoundsException your test case could check like this
#Test(expected= NegativeArrayBoundsException.class)
That means your test should throw the exception NegativeArrayBoundsException.
Alternatively you can use fail('should never come here for negative values..')
testLogicalDoc = new LogicalDocumentImpl(-4);
fail('should never come here for negative values..');
Catch AssertionError and fail otherwise:
try {
LogicalDocumentImpl testLogicalDoc = new LogicalDocumentImpl(-4);
fail("should throw");
}
catch (AssertionError e) {
}
Usually Junit test cases are meant to test that the behavior of your code in certain cases is what you expect. Therefore, for this case you expect that an exception be thrown.
Looking at the JUnit faq (http://junit.sourceforge.net/doc/faq/faq.htm#tests_7) you want to use something like the following:
#Test(expected=NegativeArrayBoundsException.class)

Categories

Resources