How to Implement Retry analyzer in try catch Block? - selenium-webdriver

Below is my code after got the exception immediately it should trigger one more time for execution but didn't execute.Without try,catch it was executing but after keep the code in try and catch RetryAnalyzer is not working as expected please anyone help me how to implement RetryAnalyzer in try,catch block
#Test(priority=4,enabled=true,retryAnalyzer=RetryAnalyzer.class)
public void TC_04() throws InterruptedException
{
try
{
extent=new
ExtentReports("/Users/anakin/workspace/Reports/MKE.html");
Login_Objects.Switch_PB2U(driver).click();
String screenshot_path = Screenshot.createScreenshot(driver);
String image = log.addScreenCapture(screenshot_path);
log.log(LogStatus.PASS, "To Stocks",image);
extent.endTest(log);
driver.closeApp();
}
catch(Exception e)
{
String screenshot_path = Screenshot.createScreenshot(driver);
String image = log.addScreenCapture(screenshot_path);
log.log(LogStatus.FAIL, "Verify Suggest Stocks ", image);
extent.endTest(log);
}
}

Catching exception in your complete test code is a bad practice. Even as in your case you are capturing screenshot in case of failure, you should use listener than catching exception.
Since retry analyzer works for failed tests, and you are cathing exceptions and thus supressing the errors, it might give the impression that your test never failed and thus the retryAnalyzer is not working.
Solution : Move code in Exception to Listeners and remove unnecessary Exception handling.

Related

The code is correct yet it needs try-catch.. why is that?

I am very new to programming and I saw this code that runs perfect with try/catch.
I thought then try/catch is not necessary, as all I know that it just for checking errors and to change the message of the compile when in error.
But when I removed it the code renders many errors and refuse to compile. So what is try/catch is really doing here? because
The code:
import java.io.FileWriter;
public class html {
public static void main(String[] args) {
try{
FileWriter fw=new FileWriter("E:\\rrr.html");
fw.write("Welcome to javaTpoint.");
fw.close();
}catch(Exception e){System.out.println(e);}
System.out.println("Success...");
}
The FileWriter class always throws an exception i.e, 'IOException',
Hence, whenever you use it IOException needs to be handled, so the
try-catch block is mandatory while using FileWriter.
What is an IOException?
An IOException is any unexpected problem the JVM encounters while attempting to run a program. Possible problems that it may encounter are:
attempting to read from a file that does not exist
attempting to write to a file that has an invalid name (a slash or a question mark in the title should do it)
attempting to read the next token in a file when there are no more tokens.
When an IOException is thrown, it means that whatever is throwing the exception (perhaps a try{}-catch block that reads data from a file) can throw an IOException, for example if the file is not found, corrupted, etc, or when the file is otherwise unable to be read, or any other of a list of issues that can occur with the IO package and it's extensions.

How can I have the soft asserts that I put in my test script be reported into the ExtentReports Report, under each failed step?

I am working with a testing framework that uses Selenium, TestNG, Java and ExtentReports for reporting.
I have a Test script which is divided into several steps and at the end of each step I have hard asserts to validate the existence of elements that I am interacting with.
I would like to use some soft asserts in order for my next steps to be able to continue executing, but I would also like to see in the ExtentReport Report, some failure indication for each step, not just at the step when the script fails.
For example, I would like to see in the report something like: step1 - passed; step2 - failed (and logged exeception for cause of error), step3 - passed etc
Currently, if I add a soft assert for an element that cannot be found at step 2 from the example above, that step is marked as passed, and I'd like it to be marked as failed, but also continue on to step 3, 4 etc.
Does anyone know how I can do that, or provide some documentation? Any help would be much appreciated.
Assuming that these steps are part of one long test method. Try using the concept of child nodes. You can set their status to fail or error etc, when an assertion fails. The issue is you will need to have a hard assertion within a try-catch block to catch AssertionError and then set the status.
ExtentTest test = extent.startTest("Hello","Yeah");
extent.loadConfig(ExtentReports.class, "extent-config.xml");
test.log(LogStatus.PASS, "Before Step details");
ExtentTest child1 = extent.startTest("Child 1");
try{
//Assertion to be placed here
child1.log(LogStatus.PASS, "Pass");
} catch(AssertionError e) {
child1.log(LogStatus.FAIL, "Fail");
}
//Add to soft assertion
ExtentTest child2 = extent.startTest("Child 2");
try{
//Assertion to be placed here
child2.log(LogStatus.PASS, "Pass");
} catch(AssertionError e) {
child2.log(LogStatus.FAIL, "Fail");
}
//Add to soft assertion
test.appendChild(child1).appendChild(child2);
test.log(LogStatus.PASS, "After Step details");
Get a report as below -
Updated
Add this method to the ExtentTestManager class and call the static method from the testng test. Though this class can be written in a simpler fashion using ThreadLocal - http://extentreports.com/docs/versions/3/java/#testng-examples
public static synchronized void updateStepResult(String childNodeDesc, Object actual, Object expected) {
ExtentTest test = extentTestMap.get((int) (long) (Thread.currentThread().getId()));
ExtentTest cn = test.appendChild(extent.startTest(childNodeDesc));
try {
assertEquals(actual, expected);
cn.log(LogStatus.PASS, "Pass");
} catch (AssertionError e) {
cn.log(LogStatus.FAIL, "Fail");
}
}

GWT RequestFactory not firing properly after using edit()

I have a problem using "fire()" with a GWT RequestFactory after I've used it to unfreeze and edit a proxy.
If I have two request factory objects and their associated contexts like this:
private SyntheticRequest req1 = requestFactory.someRequest();
private Request<xProxy> sendRequest1 = req1.something();
private SyntheticRequest req2 = requestFactory.someRequest();
private Request<xProxy> sendRequest2 = req2.something();
using "fire()" on the first request works fine:
sendRequest1.fire(new Receiver<xProxy>() {
#Override
public void onSuccess(xProxy response) {
...
if (somethingIsTrue){
xProxy x = req2.edit(response); //<-- **I think this causes a problem later, although the proxy "x" works as expected here.**
x.setSomething("something");
update();
}
});
that part runs ok because I get to the "onSuccess". But when this one runs "update()", which looks like this:
private void update(){
sendRequest2.fire(new Receiver<xProxy>(){
...onFailure...
...onSuccess...
});
}
sendRequest2 always fails, with the error
Server Error Index:0 Size:0
and I put a breakpoint in the code for the "something()" service and it never even gets to that code! There must be something about the "req2.edit()" that hurts req2 and sendRequest2, but what?
Thanks.
what is 'b'? the line xProxy x = req2.edit(b); is the first time it's mentioned? is it supposed to be xProxy x = req2.edit(response);
Anyway.. that is not the problem..
'Server Error' indicates that RequestFactory caught an exception during the processing of a request, server-side. Something (but maybe not something()) is throwing an IndexOutOfBounds exception.
If you have a look at RequestFactoryServlet.java (which you can replace with your own very easily btw) you can see it setting up a try catch block that catches all exceptions when processing a request. It passes them to 'DefaultExceptionHandler' which wraps them in a ServerFailure, and that gets returned to you GWT code as an onFailure() call.
An easy way to find where the exception is being thrown is set a breakpoint on IndexOutOfBoundsException, making sure to catch 'caught' exceptions as well as uncaught.

Dispatcher.Run vs Dispatcher.PushFrame

I have a non-ui thread that I need to pump messages on.
The normal way to do this would involve a call Dispatcher.Run() in the thread proc of my thread.
I'd like to modify this to make it more robust with regard to unhandled exceptions.
My first cut is:
for (;;)
{
var frame = new DispatcherFrame();
try
{
Dispatcher.PushFrame(frame);
break;
}
catch (Exception e)
{
frame.Continue = false;
Log("ThreadProc caught exception:\n{0}", e);
}
}
This code works and allows the dispatcher to continue pumping messages after an exception.
Does anyone know of any potential problems with this approach?
I find using a dispatcherframe can give some problems when using it with a ui thread - for example problems with focus - I think your scenario will be fine.
Have you tried catching it with:
Application.DispatcherUnhandledException
or
Dispatcher.UnhandledException
You could also try that and set Handled=true to make it continue.

Exit Application On Error in a C # Library

It is a silly question I admit. So, apologies if this wastes your time but I just cannot find out a solution.
A WinForm Application which has a Class Library. I use Log4Net dll for logging information.
On Button_Click, I call a function in the Class Library which might throw an error. So, I have the contents of the function inside a try-catch-finally block. In the catch, I write log statements (using Log4Net dll).
Now, that an error has occurred, I want a Message to be shown to the UI. And after a Message is shown, I want it to quit.
How do I pass the control from the catch block of the Class Library back to the Form code so that I display a message and then quit?
Just call throw without any parameters after you've logged the error in the exception handler in the class library and it'll rethrow the exact same exception with the same callstack etc.
Then let your form catch it and handle it as you want.
In the Class Library Method, in the catch, rethrow the exception, so that it can bubble up to the form.
In the form Button_Click wrap the Class Method call in a try catch, and in the catch display the message and exit.
The library should probably re-throw the exception after logging about it.
class Form
{
OnClick()
{
try
{
library.Routine();
}
catch(Exception e)
{
// messagebox
// exit
}
}
}
class Library
{
public void Routine()
{
try
{
// stuff
}
catch(Exception e)
{
logger.error("error in routine", e);
throw;
}
}
}

Resources