Why is my 'Wait method' not failing the TestNG test case? - java

I have purposely changed the element so it is incorrect, but my test doesn't fail in TestNG. Any ideas?
My Code:
public void waitAndClickElement(WebElement element) throws InterruptedException {
try {
element.click();
} catch (TimeoutException timeEx) {
this.wait.until(ExpectedConditions.elementToBeClickable(element)).click();
} catch (StaleElementReferenceException elementUpdated) {
this.wait.until(ExpectedConditions.elementToBeClickable(element)).click();
} catch (Exception e) {
System.out.println("Unable to wait and click on element, Exception: " + e.getMessage());
}
}
#Test(priority = 2)
public void clickOnDrivingExperiencePage() throws Exception {
basePage.waitAndClickElement(homepageHeader.link_DrivingExperiences);
}
New Code Changes:
public void waitAndClickElement(WebElement element) throws InterruptedException {
try {
this.wait.until(ExpectedConditions.elementToBeClickable(element)).click();
System.out.println("Successfully clicked on the WebElement: " + "<" + element.toString() + ">");
} catch (Exception e) {
System.out.println("Unable to wait and click on WebElement, Exception: " + e.getMessage());
Assert.assertFalse(true, "Unable to wait and click on the WebElement, using locator: " + "<" + element.toString() + ">");
}
}

} catch (Exception e) {
System.out.println("Unable to wait and click on element, Exception: " + e.getMessage());
}
You are catching all exceptions, so the test won't fail.

Related

Flux getting stuck in case of any java.lang.Error(OOM)

In flux whenever there is OOM the whole process is getting stuck until we kill it manually. I have created an example to simulate it. Please refer the following code:
#Test
public void test_Flux() {
Flux.range(1, 30)
.parallel(6)
.runOn(Schedulers.fromExecutor(Executors.newFixedThreadPool(6)))
.doOnNext(this::writeValues)
.sequential()
.blockLast();
}
private void writeValues(int val) {
if (val == 10) {
throw new OutOfMemoryError("failed here");
// throw new RuntimeException("failed here");
}
System.out.println("the thread name is :" + Thread.currentThread().getName() + " val is :" + val);
sleep(3);
}
private void sleep(int i) {
try {
Thread.sleep(i * 1000L);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException(e);
}
}
Can we crash here instead of getting stuck?

How to throw an error with transaction java

I'm doing something like this:
try {
client.restoreFromClusterSnapshot(req);
} catch (AmazonRedshiftException e) {
txUtils.execute((ts) -> {
redshiftDto.setStatus(ResourceStatus.FAILED);
redshiftDto.setStatusDetails(e.getMessage());
redshiftDto.setUpdatedOn(Timestamp.from(Instant.now()));
this.rdao.merge(redshiftDto);
return null;
});
LOGGER.error("CANNOT START REDSHIFT- " + e.getErrorMessage());
throw new AmazonRedshiftException( "CANNOT START REDSHIFT- "
+ e.getErrorMessage());
}
In this code, I'm not able to set database variable if I'm throwing an error because it is terminating my transaction. If I'll comment that throw it will work and my database value will be set. But I'll not able to throw anything. How can I do both- (throwing and setting value in DB)
What I'd do is make use of the finally clause.
AmazonRedshiftException exception = null;
try {
cluster = client.restoreFromClusterSnapshot(req);
} catch (AmazonRedshiftException e) {
exception = e;
LOGGER.error("CANNOT START REDSHIFT- " + e.getErrorMessage());
throw new AmazonRedshiftException( "CANNOT START REDSHIFT- "
+ e.getErrorMessage());
} finally {
if(exception != null) {
txUtils.execute((ts) -> {
redshiftDto.setStatus(ResourceStatus.FAILED);
redshiftDto.setStatusDetails(exception.getMessage());
redshiftDto.setUpdatedOn(Timestamp.from(Instant.now()));
this.rdao.merge(redshiftDto);
return null;
});
}
}

My Wait() method works in 'Chrome' & 'Firefox' but not in 'IE'?

My Wait() method works in 'Chrome' & 'Firefox' but not in 'IE', any ideas?
I have tried using IEDriverServer.exe both the 32bit and the 64bit(Send keys acts slow), but the following method still dosnt click on the intended target.
Please note: I know the locators are fine as listed above works in both Chrome and firefox.
public void waitAndClickFirstDrivingExperiencesOption(WebElement element) throws Exception {
WebDriverWait wait2 = new WebDriverWait(driver, 30);
Base_Page basePage = new Base_Page(driver);
try {
System.out.println(basePage.browser_type);
Boolean elementPresent = wait2.until(ExpectedConditions.elementToBeClickable(element)).isEnabled();
if (elementPresent == true) {
if (!this.browser_type.equals("firefox")) {
// Provide a slight timeout before clicking on the element
basePage.scrollToElementByLocator(element);
Thread.sleep(1000);
basePage.actionMoveAndClick(element);
} else {
Thread.sleep(500);
basePage.scrollToElementByLocator(element);
Thread.sleep(1000);
element.click();
}
}
System.out.println("Clicked on the first supercars link, using locator: " + element.toString());
} catch (StaleElementReferenceException elementUpdated) {
element = this.driver.findElement(By.xpath(".//*[#id='prd_listing']/div/li[1]/a"));
Boolean elementPresent = wait2.until(ExpectedConditions.elementToBeClickable(element)).isEnabled();
if (elementPresent == true) {
if (!this.browser_type.equals("firefox")) {
basePage.scrollToElementByLocator(element);
Thread.sleep(1000);
basePage.actionMoveAndClick(element);
} else {
Thread.sleep(500);
basePage.scrollToElementByLocator(element);
Thread.sleep(1000);
element.click();
}
}
System.out.println(
"Clicked on the first supercars link (Stale Exception), using locator: " + element.toString());
} catch (Exception e) {
System.out.println("Exception! - could not click on the first supercars link, Exception: " + e.toString());
throw (e);
} finally {
}

How to cover catch blocks?

I would like to have a full code coverage of my method writeList(), but I don't know how to cover catch blocks.
My method is :
public class ListOfNumbers {
//...another code...
public void writeList() {
try (FileOutputStream inputStream = new FileOutputStream(this.pathOut);
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(inputStream);
PrintWriter out = new PrintWriter(outputStreamWriter)) {
for (int i = 0; i < this.numbers.size(); i++) {
out.println("Value at: " + i + " = " + this.numbers.get(i));
}
} catch (final ArrayIndexOutOfBoundsException e) {
ListOfNumbers.LOGGER.error("Caught ArrayIndexOutOfBoundsException: " + e.getMessage(),
e);
} catch (final FileNotFoundException e) {
ListOfNumbers.LOGGER.error("Caught FileNotFoundException: " + e.getMessage(), e);
} catch (final IOException e) {
ListOfNumbers.LOGGER.error("Caught IOException: " + e.getMessage(), e);
}
}
}
To do it, If I were you, I would rewrite my code to make it more testable by moving the code that write the numbers into a different method, in order to mock this new method to make it throw whatever you want using Mockito.
So your code could be something like that:
public void writeList() {
try (FileOutputStream inputStream = new FileOutputStream(this.pathOut);
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(inputStream);
PrintWriter out = new PrintWriter(outputStreamWriter)) {
// Delegate the way to write the numbers to this new method
writeNumbers(out);
} catch (final ArrayIndexOutOfBoundsException e) {
ListOfNumbers.LOGGER.error(
"Caught ArrayIndexOutOfBoundsException: " + e.getMessage(), e
);
} catch (final FileNotFoundException e) {
ListOfNumbers.LOGGER.error("Caught FileNotFoundException: " + e.getMessage(), e);
} catch (final IOException e) {
ListOfNumbers.LOGGER.error("Caught IOException: " + e.getMessage(), e);
}
}
/**
* The new method that is protected here but could also be package protected
* but cannot be private to be able to override it.
*/
protected void writeNumbers(PrintWriter out) {
for (int i = 0; i < this.numbers.size(); i++) {
out.println("Value at: " + i + " = " + this.numbers.get(i));
}
}
Then your unit test could be:
#Test
public void causeAIOException() {
ListOfNumbers lon = // Create your instance here
// Create a Spy to be able to mock the method writeNumbers
ListOfNumbers listOfNumbers = Mockito.spy(lon);
// This will make any call to writeNumbers throw a IOException
Mockito.doThrow(IOException.class).when(listOfNumbers)
.writeNumbers(Matchers.any(PrintWriter.class));
// Call the method on the spy
listOfNumbers.writeList();
}
NB: In case of FileNotFoundException, you could simply provide an existing folder as pathOut as it is one of the cases for which new FileOutputStream will throw a FileNotFoundException and it is easy to reproduce.
class ListOfNumbers {
public void writeList() throws ArrayIndexOutOfBoundsException,FileNotFoundException,IOException {
try (FileOutputStream inputStream = new FileOutputStream(this.pathOut);
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(inputStream);
PrintWriter out = new PrintWriter(outputStreamWriter)) {
for (int i = 0; i < this.numbers.size(); i++) {
out.println("Value at: " + i + " = " + this.numbers.get(i));
}
}
}
public class Main{
public static void main(String [] args){
try{
ListOfNumbers list=new ListOfNumbers();
try{
list.writeList();
}
} catch (ArrayIndexOutOfBoundsException e) {
ListOfNumbers.LOGGER.error("Caught ArrayIndexOutOfBoundsException: " + e.getMessage(),
e);
} catch (FileNotFoundException e) {
ListOfNumbers.LOGGER.error("Caught FileNotFoundException: " + e.getMessage(), e);
} catch (IOException e) {
ListOfNumbers.LOGGER.error("Caught IOException: " + e.getMessage(), e);
}
}
}
}

Validate COMPLETE XML Against XSD

I want to validate my XML against my XSD COMPLETELY, meaning that I want the file to continue validating from the same point where it had thrown an exception.
This is my code :
public void validate(File file) {
try {
Source xmlFile = new StreamSource(file);
try {
System.out.println("Processing : " + file.getAbsolutePath());
System.out.println(validator);
validator.validate(xmlFile);
// stringBuffer.append(" is valid");
} catch (SAXException e) {
fileWriter.write("\n\n\n" + file.getAbsolutePath());
System.out.println(xmlFile.getSystemId() + " is NOT valid");
System.out.println("Reason: " + e.getLocalizedMessage());
fileWriter.write("\nReason: " + e.getLocalizedMessage());
if (e instanceof SAXParseException) {
fileWriter.write(" (Line : "
+ ((SAXParseException) e).getLineNumber()
+ ", Col : "
+ ((SAXParseException) e).getColumnNumber() + ")");
}
fileWriter.flush();
validate(file);
}
} catch (Exception exception) {
exception.printStackTrace(System.out);
}
}
Here according to this snippet, after JUST ONE EXCEPTION the code returns the error and stops validating further XML.. But is there any way to get all the errors of the XML against the XSD? In short to continue validating from the cursor where it had thrown an exception.
ANY WAY OUT??
Thanks!
The behavior of the default error handler is to stop processing after the first fatal error is encountered by throwing a SAXException. To alter this behavior, implement your own ErrorHandler and register it with your validator.
This is an example that just dumps the exceptions to standard output, but you would probably want to replace it with a more intelligent reporting mechanism.
class CustomErrorHandler implements ErrorHandler {
public void fatalError(SAXParseException e) throws SAXException {
System.out.println(e.toString());
}
public void error( SAXParseException e ) throws SAXException {
System.out.println(e.toString());
}
public void warning( SAXParseException e ) throws SAXException {
System.out.println(e.toString());
}
}
And then:
validator.setErrorHandler(new CustomErrorHandler());

Categories

Resources