Can we handle Assert fail in try and catch in testNG - java

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
}

Related

Nested try blocks with catches after finally

I want to write a code like this:
try {
try {
someStuffThatCausesBusinessExceptions();
} finally {
try {
cleanUp();
} catch (Exception e) {
// I don't really care
}
}
} catch (BusinessLogicException e) {
// work with exception
// cleaning up must be done by that point (or at least tried to)
}
Will exceptions from business logic survive the possible hiatus during cleanUp? Is there a better way to ignore all the possible exceptions from cleanUp?
A catch block will only catch Throwables that were thrown in its corresponding try block. Thus, your exceptions thrown in the surrounding try block will be preserved and caught in the outer catch block.
Yes. Your exception will reach the last catch. However, this structure seems weird an non-idiomatic to me, i guess i would even prefer having cleanUp() more than once in that code over having 3 tries.
There are two cases-:
1. if excetpion occurs from mehtod someStuffThatCausesBusinessExceptions only then it will be caught in your outer catch block.
2. if the methods someStuffThatCausesBusinessExceptions and cleanUp both throw exceptions then the exception thrown from try block is suppressed.
Yes!! there is better way.You can use try-with-resources statement.
Please refere to this link.
https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html

Closing connection's object in other class through a method in finally block

I am using Sonar tool to analyze the coding standard in an existing Application where I met a Sonar Rule: "Close the resources" where Connection's object conn is the culprit.
As we know we should close the Connection object using conn.close(); but in the Application a method to release the connection has been called.
Below is the piece of code where Connection object is closed through a method named releaseConnection() in finally block.
finally {
try {
OtherClass.releaseConnection(conn); // Line: 50 Here is the call to close the conn
}
catch (SomeException se) {
LOGGER.error(" Exception while releaseConnection in add() method : ",se);
}
}
Closing method:
public static void releaseConnection(Connection conn) throws DBException {
if (conn!=null) {
try {
if (!conn.isReadOnly()){
conn.commit();
}
} catch (SQLException e) {
LOGGER.error("Error while commiting the connection. " + e);
rollback(conn);
throw new SomeException(e,SOMETHING);
} finally {
try {conn.close();} catch (SQLException se){
LOGGER.error("releaseConnection() Error " + se);
}
}
}
}
Here's the list of my concern:
As this existing implementation is doing the correct thing (Correct me if I am wrong) is it really need to change the code as per Sonar suggestion.
If really I need to follow the Sonar's suggestion what should be the best way.
UPDATE:
How can I just ignore/bypass some certain code or rule and apply in my above code.
Lets say I want to ignore Line: 50, how can I do that?
I do not want to mess with the above piece of code but I really wanna ignore this and make my issues lesser. Thanks in advance.
You are actually encountering a limitation of the symbolic execution engine (which is used by this rule under the hood) : https://jira.sonarsource.com/browse/SONARJAVA-1591
What is happening here is that we approximate the flow of execution in try/catch/finally by having a path of execution skipping the whole try block (to simplify the handling of flow) and that results in the false positive you mentioned because we don't see the call to your method that would prevent the issue of being raise.
That's right! Sonar does not check if any method is called from finally block to close the resources. It simply checks the closing of resources.

TestNG try/catch not working properly

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.

How do you continue your program even if an exception occurs?

In my program I have to constantly access the hard drive thousands of times to view images (no way around it), occasionally my program gets tripped up on a "file not found IO Exception" most likely because of the many modifications I'm making to the images and re saving quickly. How do I continue my program even if this error occurs, because currently it causes my program to stop?
Code:
filepattern=imageLocation+temp+"image.jpg";
File outputfile = new File(filepattern);
BufferedImage img = null;
try {
img = ImageIO.read(outputfile);
} catch (IOException e) {
}
Note: I have fixed the problem by making sure the file exists first. Thanks for all your help!
Catch the exception and handle it as needed.
try {
// your code
} catch (<Expected exception> e) {
// handle the exception
}
Surround the statement with a try catch.
This will stop the code from crashing and in the catch block you can write code to deal with the failure.
There are 3 key words
try {}
executes the block that can cause problems
catch (Exception ex) {}
executes code to handle specific exceptions. Instead of Exception you can handle specific exception types
finally {}
executes cleanup code. Even if exception occurs and breaks the execution flow in try block, this code will always execute.
You might try something like the fragment below. Of course, you will want to encapsulate the actual reading in a try / catch / finally block to make sure you close the file
try {
filesTried++;
[you code]
} catch (IOException e) {
fileErrors++;

Is there a java equivalent of vb on error/ resume next pattern?

In VB, for error catching there is
Public Sub MySub()
On Error GoTo Errr
'do stuff
Errr:
'handle error
Resume Next
End Sub
which uses the magnificent Resume Next command.
In Java, you have a try catch block
try
{
//some code
}
catch (Exception e)
{
//handle error
}
which seems to be equivalent to the VB error catching, but specifically without the Resume Next option, so Java just quits the entire code block after the error, instead of trying to run the rest of the code after the error. Is there any way to get the power of Resume Next in Java? Thanks!
Just put the code that you want to run regardless of any error after the catch block.
try {
// stuff that could cause error
} catch(Exception e) {
// handle error
}
// do stuff
If you're going to throw an exception from the catch block but you still want the "do stuff" code to run, you can put it in a finally block like this:
try {
// stuff that could cause error
} catch(Exception e) {
// throw exception here
} finally {
// do stuff that will run even when the exception is thrown
}
There is no equivalent in Java, to VB resume statements; in VB depending on the error case, you can choose to resume at a particular label within your code, in order to re-run the code after fixing the error, similar to a goto statement; this is not possible in java, except when you're inside a loop, then you can use the continue to a defined label block.

Categories

Resources