I have a test case:
Assert.assertTrue(test .verifyNoDrillDisplayForCourses());
and a boolean method verifyNoDrillDisplayForCourses which verifies element("xyz") is not displayed,
try{
if(element("xyz"). isDisplayed())
return false;
else return true;
}
catch (Exception e)
{
return false;
}
}
But the assertion fails as java .lang .AssertionError:expected [true] but found [false]. I am unable to figure out why?
The isDisplayed() method will throw an StaleElementReferenceException, if the given element is not in the DOM anymore. So you have to change the catch statement to return true;.
If you're testing for the presence of an element, if it's not found an exception will be thrown. So if you find it you're returning false, if you can't find it you're also returning false.
When testing for non-presence of an element you should have the catch block return true!
try{
if(element("xyz").isDisplayed()) {
return false;
} else return true;
}
catch (Exception e)
{
return false;
}
}
I believe your if statement is missing correct formatting from what you copied over.
I've amended it above, but in case try it like this:
if(element("xyz").isDisplayed()) {
return false;
} else return true;
Following code helped:
public boolean verifyNoelement()
{
try
{
if(element("element").isDisplayed())
{
return false;
}
return false;
}
catch(Exception e)
{
logMessage("No element displayed");
return true;
}
}
Related
I have class where I am written code to create a new category and if category not found it will throw "CategoryNotFoundException". I have written the test cases but it was not passed.
If I omit "expected= CategoryNotFoundException.class" from my JUNIT test case it will pass. But I don't want to change any portion in my Test cases. I tried by throwing the exception from my implemented class but still it is not passed.I am stucking there to pass the TestCase.
DAO code::
#Transactional
public boolean createCategory(Category category){
//boolean isInserted=false;
Session session=this.sessionFactory.getCurrentSession();
session.save(category);
return true;
//return isInserted;
}
Tried with the below code as well but TC not passed:
#Transactional
public boolean createCategory(Category category){
//boolean isInserted=false;
try{
Session session=this.sessionFactory.getCurrentSession();
Integer isInsertedWrapper=(Integer)session.save(category);
if(isInsertedWrapper>0){
return true;
}else{
throw new CategoryNotFoundException("CategoryNotFoundException");
}
}
catch(Exception ex){
return false;
}
}
JUNIT Code::
#Test(expected= CategoryNotFoundException.class)
#Rollback(true)
public void testCreateCategoryFailure() throws CategoryNotFoundException {
categoryDAO.createCategory(category);
Category savedCategory = categoryDAO.getCategoryById(2);
assertNotEquals(category, savedCategory);`enter code here`
}
You are trying to throw an exception but you are catching also, so you should rethrow If it is necessary, so you should try to do this:
#Transactional
public boolean createCategory(Category category){
//boolean isInserted=false;
try {
Session session=this.sessionFactory.getCurrentSession();
Integer isInsertedWrapper=(Integer)session.save(category);
if(isInsertedWrapper>0){
return true;
}else{
throw new CategoryNotFoundException("CategoryNotFoundException");
}
} catch(CategoryNotFoundException exc) {
throw exc;
} catch(Exception ex){
return false;
}
}
I want to check that an element is not displayed. I have written the following code :
public boolean verifyelementNotDisplayed() {
try
{
if(element("element").isDisplayed())
return false;
else
{
logMessage("element not displayed");
return true;
}
}
catch(Exception e)
{
return false;
}
}
But my test fails.
Try this snippet:
public boolean verifyelementNotDisplayed() {
try{
return(!element("element").isDisplayed());
catch(Exception e){
return false;
}
}
And have a look at the is displayed method:
How does Selenium WebDriver's isDisplayed() method work
or:
Where is the implementation for the WebElement.isDisplayed() method in Selenium?
The following code worked
public boolean verifyNoelement() {
try
{
if(element("element").isDisplayed())
{
return false;
}
return false;
}
catch(Exception e)
{
logMessage("No element displayed");
return true;
}
}
Java validation of a URL through Regular Expression
String url = "https://my-company-08.vv.xyz.com/abc.svc/Abcdef(id='{0}',text='ABC.XYZ')?$query=xxxx&$format=xml";
URLs are potentially complex beasts with many possible variants. If you write your own regex parser you will most likely fail to cover all cases. Use the built in URI or URL class to do it for you...
private static boolean isValidUri(String candidate) {
try {
new URI(candidate);
return true;
} catch (URISyntaxException e) {
e.printStackTrace();
return false;
}
}
With URL
private static boolean isValidUrl(String candidate) {
try {
new URL(candidate);
return true;
} catch (MalformedURLException e) {
e.printStackTrace();
return false;
}
}
Your specific syntax errors....
// returns false, error at character 51 which is the first (
System.out.println(isValidUri("https://my-company-08.vv.xyz.com/abc.svc/Abcdef(id= '{sd54asds2f21sddf}',text='ABC.XYZ')?$query=myClient&$format=xml"));
// returns true without the (id= '{sd54asds2f21sddf}',text='ABC.XYZ') stuff
System.out.println(isValidUri("https://my-company-08.vv.xyz.com/abc.svc/Abcdef?$query=myClient&$format=xml"));
The following code is supposed to return the last value in arraylist if it has one, if not, how could I return the exception?
public int getLast() {
try {
return arrl.get(arrl.size() - 1);
} catch (Exception e) {
System.out.println("Caught "+ e);
}
}
arrl here is ArrayList
I excuted above code and received "error: missing return statement"
You have return statement in your try{} but not in your catch(){}, this gives you the exception. You can include the return in both or return after the try catch.
public int getLast() {
Object o=null;
try {
o=arrl.get(arrl.size() - 1);
} catch (Exception e) {
System.out.println("Caught "+ e);
}
return o;
}
Also to return the exception back to the caller you need to rethrow it from your method, or not catch it at all
catch (Exception e) {
System.out.println("Caught "+ e);
throw e;
}
or
public int getLast() {
return arrl.get(arrl.size() - 1);
}
But I doubt any exception being thrown from this statement except for IndexOutOfBoundsException
You don't return an exception.. You throw it back to the caller.
public int getLast() {
try {
return arrl.get(arrl.size() - 1);
} catch (Exception e) {
System.out.println("Caught "+ e);
throw e;
}
}
Your code gives you compilation error because you are not returning anything in catch block. throwing would be good enough.
Alternatively, don't catch it, any uncaught exceptions will be automatically thrown back to the caller. So below code would also throw the exception back to the calling method.
public int getLast() throws Exception {
return arrl.get(arrl.size() - 1);
}
There's really no good reason for the try/catch block here at all. Just let the NPE or AIOOBE be thrown to the caller and let him deal with them.
You are getting this error because if the first return in the try-part didn't work the compiler doesn't know what it should return instead. You need either another return or exception rethrow in the catch-part:
public int getLast() {
try {
return arrl.get(arrl.size() - 1);
} catch (Exception e) {
System.out.println("Caught "+ e);
// You need to return something here or rethrow the e...
}
// or return something here.
}
...but this kind of logic is bad any way and this function shouldn't throw exceptions at all. I'd be better to check it the array has any items before getting the last one. If you run this in a loop the performace might be really bad if the error is thrown frequently.
public int getLast() {
if (arrl != null && arrl.size() > 0) {
return arrl.get(arrl.size() - 1);
}
else {
return -1;
}
}
or
public Integer getLast() {
if (arrl != null && arrl.size() > 0) {
return arrl.get(arrl.size() - 1);
}
else {
return null;
}
}
In this scenario, the only exceptions that may be raised are NPE due to arrl being null and an indexing error if the list is empty. If the class is properly initialised, the NPE shouldn't happen at all. The other exception is a client error, which may be passed on to the caller. Alternatively, one might consider returning null (after changing int to Integer):
public Integer getLast() {
try {
return arrl.get(arrl.size() - 1);
} catch (IndexOutOfBoundsException ioobe) {
return null;
}
}
There is the possability that your method can not return a value (for what reasons ever). In this case you should use now java.lang.Optional (Java-8) as return type:
public Optional<Integer> getLast() {
try {
return Optional<T>.ofNullable(arrl.get(arrl.size() - 1));
} catch (Exception e) {
e.printStackTrace();
return Optional.empty();
}
}
This way you will force the user of your method to deal with the situation of not having a result to be returned. (BTW: you should not catch Exception, mostly never. Instead take care that arrl is not null and arrl.size() is within the limits. Handling exceptions is for the... umm exeptional cases, not to be used as control statement.)
I am testing a function that permit to connect to FTP server.
Here is one of my test who works properly:
#Test
public void connectTestValid()
{
assetSource.setPassword("password");
assetSource.setUsername("user");
assetSource.setServerAddress("127.0.0.1");
assetSource.setServerPort(21);
connectionSuccess = false;
connectionSuccess = ftpFolderTest.connectFTP(ftpClient);
if (!connectionSuccess)
{
fail("Expected Connection success");
}
}
I want to test if the connectFTP() method throw an exception when the serverAddress is invalid.
Here is my test:
#Test(expected = Exception.class)
public void connectTestInvalidServerAddress()
{
assetSource.setPassword("password");
assetSource.setUsername("user");
assetSource.setServerAddress("1");
assetSource.setServerPort(21);
connectionSuccess = false;
connectionSuccess = ftpFolderTest.connectFTP(ftpClient);
}
Here is my function:
protected boolean connectFTP(FTPClient ftp)
{
try
{
ftp.connect(getAssetSource().getServerAddress());
if (!ftp.login(getAssetSource().getUsername(), getAssetSource().getPassword()))
{
logger.error("Login Failed");
ftp.disconnect();
return connectionSuccess = false;
}// if
if (!FTPReply.isPositiveCompletion(ftp.getReplyCode()))
{
logger.error("Connection Failed");
ftp.disconnect();
return connectionSuccess = false;
}// if
}
catch (Exception e)
{
e.printStackTrace();
return connectionSuccess = false;
}
return connectionSuccess = true;
}
Presently, the test doesn't work.
Thanks for your help!
The reason the test is not passing is that it is expecting an Exception to be thrown, but the exception is being caught inside the 'connectFTP' method, which is then returning false.
Whether you return false when connection fails or throw an exception depends on the semantics of your code. Based on the boolean return value, it seems like you're expecting false to be returned when there is an exception. In that case you'll want to do
org.junit.Assert.assertFalse(connectionSuccess);
instead of using (expected = Exception.class) in the #Test annotation.
it looks like you're catching an exception by yourself in your code
If you call the method 'connectFTP' from outside (it doesn't matter whether its a junit or not, it just won't throw an exception.
That's why your JUnit doesn't work.
BTW, it would be better not to work directly with Exception, but with its subtype relevant for your case.