How to skip a test and not fail it - java

In the middle of the test, if the condition of the test is not satisfied, how can I skip the test without failing it.
I try to throw an exception and it is marked as failed.

You will need to use the assume:
org.junit.Assume.assumeTrue(condition());
If this fails your test will be ignored.
I recommend doing this assume in your #Before method
Hope this helps

I think you can use some thing like
try {
///some process
try {
///your middle test
}catch (excetion e){
}
}catch (excetion e){
}
If the middle test is failed the rest will work

Related

SonarQube rule "Methods returns should not be invariant" with catch block

I'm using latest SonarQube server 9.4 and it constantly reports "Refactor this method to not always return the same value." - java:S3516 in piece of code like this:
try
{
FileUtils.moveFile(dcomExportFile, destination);
}
catch(IOException e)
{
Logger.error(this, "Could not move file {} to {}, future job runs might fail as well",
dcomExportFile.getAbsolutePath(), destination.getAbsolutePath());
return false;
}
return true;
Which is very strange because method FileUtils.moveFile can throw IOException and in this case method returns false.
Any idea?
Thx!
I would move the return false statement to outside and after the catch (where return true is now). And move the return true to immediately follow the Fileutils call in the try block, like this:
try
{
FileUtils.moveFile(dcomExportFile, destination);
return true;
}
catch(IOException e)
{
Logger.error(this, "Could not move file {} to {}, future job runs might fail as well",
dcomExportFile.getAbsolutePath(), destination.getAbsolutePath());
}
return false;
It's confusing and arguably bad style to return from within a catch block anyway.
I'm not sure that in this case not letting the exception be thrown is a great idea because this seems like the sort of error I would want to bubble up, where having a return value lets it get lost too easily. Maybe it's not so bad if logging the error is the only thing the code does to handle this.
I think it may not be good idea to just catch & log exception & return false. You might need to throw exception back to caller of your method.
Good example which comes in my mind is list.add(..) where if operation is success it returns true but in case of any failure it throws exceptions to caller instead of returning false.
I found solution - scanning with correct sonar.java.libraries path resolves this issue.

Is there a point to handle exceptions in selenium besides for logging purposes?

I am finding it hard to understand the point of exception handling in selenium.
For example, if I try to click on an element, and the element could not be found then NoSuchElementException occurs.
I can catch the exception, throw new RunTimeException, or do nothing. The result will be the same ( the program will fail and stop ).
Why would I bother to handle such an exception?
Am I missing something here?
thanks
public void clickOnElement(MobileElement element, Integer waitInSeconds){
waitInSeconds = (waitInSeconds != null ? waitInSeconds : this.secondsToWait);
try {
waitFor(ExpectedConditions.elementToBeClickable(element),waitInSeconds);
element.click();
} catch (Exception e) {
System.out.println("Could not click on element");
e.printStackTrace();
}
}
Exception handling for Selenium is a great way to proof your tests against unexpected conditions. For example, you can try to find the element again if it is no longer attached to the page, for example after a javascript is executed that changes something in the element.
try{
driver.findElement(By.id("MyId")).click();
} catch (StaleElementReferenceException e){
driver.findElement(By.id("MyId")).click();
}
Or, for example, you can ignore if an element does not appear, for example, a GDPR overlay at the top of the page after logging in.
try {
wait.until(ExpectedConditions.presenceOfElementLocated(By.id("gdpr_overlay")));
} catch (TimeoutException ignored){
}
This will ignore the exception thrown by the wait if the overlay does not appear and continue to run your test.
Exceptions are very useful features, far more useful than just for logging, you should look it up.
You can do whatever you want in the catch block, you can try to click a different element if the first one failed, redirect to another page... The possibilities are endless really.
Advice: Avoid generic exceptions, you should catch specific exceptions and react accordingly, and in the last catch block you can do generic Exception e and throw an error.
Firstly ExceptionHandling is not a concept of Selenium but it is related to JAVA. Now coming to the usage of handling exceptions it has a lot of depth to the concept which you will understand while constructing frameworks but as of now it is important to understand by handling exceptions you can continue to execute your code without JVM terminating the rest when it comes across an exception.
try{
}
catch{
}
finally
{
}
Finally is also very helpful when you always want to execute a block of code irrespective of whether ur scenario is going to pass or fail for example like driver.close().
Hope that helped ... Happy coding :)

Java - TestNG : Is It Wrong to use testng Assert.fail() in a catch block

I came across a code written by someone with Assert.fail("some text") in a catch block. This is my code:
try {
//WebDriver code here which interacts with WebElements
//When an exception occurs in this try block, it will be caught in
//the catch and further catch block has Assert.fail()
} catch (Exception e) {
Assert.fail("failed to click 'Webelement' ");
}
I somehow felt this is not right way to do it. Am i wrong?
Note: Not exactly a duplicate of Is Assert.Fail() considered bad practice , As i am not expecting any Exception. If any exception occurs i need to fail the test case
Though it's syntactically not incorrect. But you should preferably rephrase your tests to use expectedException instead and be specific about the exception is thrown as well. For e.g. :
If your method fromTest() when called with "test" as an argument could throw an NumberFormatException, then your test definition for such behaviour should be :
#Test(expectedExceptions = NumberFormatException.class)
public void testMethod() {
System.out.println("About to throw an exception!");
fromTest("test");
}
Note: If you believe that the exception may so happen within your test execution itself instead of any other method being called from it. I would suggest to not catch it. Let it fail and then you shall fix it.

catch a exception with specific message

Is there a better way for catching specific Exception with a message then doing this:
try{
methodThatWillProbablyThrowASocketException();
} catch(SocketException e){
if(e.getMessage().contains("reset")){
// the connection was reset
// will ignore
} else{
throw e;
}
}
For example the HttpStatusException gives me the Method getStatusCode() where i can easily compare if the error status was 404 or 502 and the can decide what to do:
try{
methodThatWillProbablyThrowAHTTPException();
} catch(HttpStatusException e){
if(e.getStatusCode() == 404){
// not found, will not continue
}
if else(e.getStatusCode() == 502){
// server errror, try again
} else{
throw e;
}
}
Most other Exceptions dont give me prober Methods, just the Message.
So my question is, is it the right way to do it? With String compares? Or is there a better way?
Just do one thing .
Collect all types of exception that are likely to be occur for your project.
Make a separate class by extending Exception.
Override the getCause() method.
http://docs.oracle.com/javase/6/docs/api/java/lang/Throwable.html#getCause%28%29
public Throwable getCause()
Define codes you want for different exceptions Like null-pointer 101 ,, so on......
The use that class every where . So you have to write exception only once and you can use with as many projects.
After building the class it will be reusable for all your needs
If you getting new conditions, update this class only and all the things will be done
This is a better solution according to me...
This way you can get functionality for which you are looking. you have to make it by yourself.
Relying on code or status code is fine but relying on message could be problematic as the message can change.
You should look to refactor and define multiple exceptions or define codes for different scenarios.

Anyone can tell me what's wrong with this pseudo code?

I am not familiar with JUnit so not sure if that's the problem of assertTrue(b_exception);, because if I put an System.out.println("something"); there, it would print out "something"... Thanks!!
Please note that it is pseudo code, focus on the logic.
b_exception = false;
try{
somethingThrowError();
}catch(Error e){
b_exception = true;
}
assertTrue(b_exception);
I don't know what the problem is with your code because you haven't stated how it fails to fulfill your expectations, but the correct idiom for testing that an exception is thrown is to use JUnit 4's annotations:
#Test(expected=SpecificError.class)
public void testError(){
somethingThrowError();
}
I can only guess that you are looking for this:
try{
somethingThrowError();
fail("Exception expected");
}catch(AsSpecificAsPossibleException e){
//should happen, OK
//optionally assert exception message, etc.
}
Also note that catching an Error is a bad idea, use as specific exception as you can.
UPDATE: #Michael Borgwardt's answer is actually even better, but only if there is nothing except a single line in your test (nothing else that can throw). Also #Test(expected does not allow you to perform extra exception message assertions (but should you?)
Not sure what you think is wrong with that code.
The assertTrue will always be executed, as will the System.out.println.
It - the assertTrue - will signal an error if the argument is not true, or "pass the test" if the argument is true.
Maybe you should use System.out.println("b_exception = " + b_exception); to see what is happening.

Categories