Asserting in the example below - java

testLogicalDoc = new LogicalDocumentImpl(-4);
assertTrue(testLogicalDoc==null);
In my code above, I have an assert condition with which I want to make sure I don't create my object with negative size. It is a stringBuilder beneath the covers which throws NegativeArrayBoundsException for a size less than zero. But my junit test fails here. I don't know any other way of making sure an object is not created with a negative size.
Any thoughts on how this could be tested ? or should it be a Junit test at all ??
Many thanks,
-Pan
EDIT:
#Test(expected=NegativeArraySizeException.class)
public void testCreate4b()
{
LogicalDocumentImpl testLogicalDoc = new LogicalDocumentImpl(-4);
}
I'm catching the exception in the LogicalDocumentImpl class but still this test fails with an assertion error but only succeeds when I do a try catch on assertion error ..why is that so ??

if you are throwing NegativeArrayBoundsException your test case could check like this
#Test(expected= NegativeArrayBoundsException.class)
That means your test should throw the exception NegativeArrayBoundsException.
Alternatively you can use fail('should never come here for negative values..')
testLogicalDoc = new LogicalDocumentImpl(-4);
fail('should never come here for negative values..');

Catch AssertionError and fail otherwise:
try {
LogicalDocumentImpl testLogicalDoc = new LogicalDocumentImpl(-4);
fail("should throw");
}
catch (AssertionError e) {
}

Usually Junit test cases are meant to test that the behavior of your code in certain cases is what you expect. Therefore, for this case you expect that an exception be thrown.
Looking at the JUnit faq (http://junit.sourceforge.net/doc/faq/faq.htm#tests_7) you want to use something like the following:
#Test(expected=NegativeArrayBoundsException.class)

Related

Java Selenium - Is it possible to take a screenshot if something fails in #AfterMethod?

Generally, I would like to take a screenshot if something fails in #AfterMethod, before closing the browser, etc.
I run Test and it passes, but it changes some data, and in #AfterMethod this data is restored to a basic state, but sometimes it fails and stack sometimes is not enough to figure out what exactly caused the problem. Because of the above, I would like (if it is possible) to take a screenshot if #AfterMethod fails.
By "something fails in #AfterMethod" I mean e.g. encountering an exception.
every fail errors comes from AssertionError Exception if you want to take a screenshot you should catch the AssertionError
how? make try catch block like this
try{
Assert.assertTrue(false) // this throws thread into the catch block
}catch(AssertionError error){
driver.takeSreenshot() // I don't remember method name
//and in the end throw again to fail it in reality
throw error
}

How to correctly handle a spark.sql.AnalysisException

I've been using Spark Dataset API to perform operations on a JSON to extract certain fields as needed. However, when the specification that I provide to let spark know what field to extract goes wrong, spark spits out an
org.apache.spark.sql.AnalysisException
How can unchecked runtime exceptions be handled in a distributed processing scenario like this ? I understand that throwing a try-catch would get things sorted but what is the recommended way to handle such a scenario
dataset = dataset.withColumn(current, functions.explode(dataset.col(parent + Constants.PUNCTUATION_PERIOD + child.substring(0, child.length() - 2))));
In scala, you should simply wrap the call in a Try and manage Failure. Something like:
val result = Try(executeSparkCode()) match {
case s: Success(_) => s;
case Failure(error: AnalysisException) => Failure(new MyException(error));
}
Note 1: If your question implies how to manage exception in scala, there are a lot of doc and post about this subject (i.e. don't throw). For example, you can check that answer (of mine)
Note 2: I don't have a scala dev env right here, so I didn't test this code)
In java there is a tricky situation however: the compiler doesn't expect an AnalysisException which is unchecked so you cannot catch this exception specifically. Probably some scala/java misunderstanding because scala doesn't track checked exceptions. What I did was:
try{
return executeSparkCode();
} catch (Exception ex) {
if(ex instanceOf AnalysisException){
throw new MyException(ex);
} else {
throw ex; // unmanaged exceptions
}
}
Note: In my case, I also tested the content of the error message for a specific exception that I must managed (i.e "path does not exist") in which case I return an empty dataset instead of throwing another exception. I was looking for a better solution and happened to get here...

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.

Java - ignore exception and continue

For my Java application, I am creating an instance of a user information object and populating it with a service that I don't control the source for.
The code looks like this:
// username given as parameter
UserInfo ui = new UserInfo();
try {
DirectoryUser du = LDAPService.findUser(username);
if (du!=null) {
ui.setUserInfo(du.getUserInfo());
}
} catch (Exception e) {
// Whatever
}
If LDAPService.findUser() can't locate a user, it will throw a NullPointerException and grind the rest of my application to a stop. It's okay if the user information isn't populated, so I want to be able to continue without causing everything else to start throwing exceptions.
Is there a way to do this?
I've upvoted Amir Afghani's answer, which seems to be the only one as of yet that actually answers the question.
But I would have written it like this instead:
UserInfo ui = new UserInfo();
DirectoryUser du = null;
try {
du = LDAPService.findUser(username);
} catch (NullPointerException npe) {
// It's fine if findUser throws a NPE
}
if (du != null) {
ui.setUserInfo(du.getUserInfo());
}
Of course, it depends on whether or not you want to catch NPEs from the ui.setUserInfo() and du.getUserInfo() calls.
You could catch the NullPointerException explicitly and ignore it - though its generally not recommended. You should not, however, ignore all exceptions as you're currently doing.
UserInfo ui = new UserInfo();
try {
DirectoryUser du = LDAPService.findUser(username);
if (du!=null) {
ui.setUserInfo(du.getUserInfo());
}
} catch (NullPointerException npe) {
// Lulz # your NPE
Logger.log("No user info for " +username+ ", will find some way to cope");
}
You are already doing it in your code. Run this example below. The catch will "handle" the exception, and you can move forward, assuming whatever you caught and handled did not break code down the road which you did not anticipate.
try{
throw new Exception();
}catch (Exception ex){
ex.printStackTrace();
}
System.out.println("Made it!");
However, you should always handle an exception properly. You can get yourself into some pretty messy situations and write difficult to maintain code by "ignoring" exceptions. You should only do this if you are actually handling whatever went wrong with the exception to the point that it really does not affect the rest of the program.
It's generally considered a bad idea to ignore exceptions. Usually, if it's appropriate, you want to either notify the user of the issue (if they would care) or at the very least, log the exception, or print the stack trace to the console.
However, if that's truly not necessary (you're the one making the decision) then no, there's no other way to ignore an exception that forces you to catch it. The only revision, in that case, that I would suggest is explicitly listing the the class of the Exceptions you're ignoring, and some comment as to why you're ignoring them, rather than simply ignoring any exception, as you've done in your example.
You are actually ignoring exception in your code. But I suggest you to reconsider.
Here is a quote from Coding Crimes: Ignoring Exceptions
For a start, the exception should be logged at the very least, not
just written out to the console. Also, in most cases, the exception
should be thrown back to the caller for them to deal with. If it
doesn't need to be thrown back to the caller, then the exception
should be handled. And some comments would be nice too.
The usual excuse for this type of code is "I didn't have time", but
there is a ripple effect when code is left in this state. Chances are
that most of this type of code will never get out in the final
production. Code reviews or static analysis tools should catch this
error pattern. But that's no excuse, all this does is add time to the
maintainance and debugging of the software.
Even if you are ignoring it I suggest you to use specific exception names instead of superclass name. ie., Use NullPointerException instead of Exception in your catch clause.
You can write a try - catch block around the line you want to have ignored.
Like in the example code of yours. If you just continue your code below the closing bracket of the catch block everythings fine.
LDAPService should contain method like LDAPService.isExists(String userName) use it to prevent NPE to be thrown. If is not - this could be a workaround, but use Logging to post some warning..
Printing the STACK trace, logging it or send message to the user, are very bad ways to process the exceptions. Does any one can describe solutions to fix the exception in proper steps then can trying the broken instruction again?

Java coding practice, runtime exceptions and this scenario

In the following scenario, I was trying to see how to handle this code and it how it relates to Runtimexception. I have read that is generally better to throw runtime exceptions as opposed to rely on static exceptions. And maybe even better to catch a static checked exception and throw an unchecked exception.
Are there any scenarios where it is OK to catch a static exception, possibly the catch-all Exception and just handle the exception. Possibly log an error message and continue on.
In the code below, in the execute1 method and execute2 method, let us say there is volatile code, do you catch the static exception and then rethrow? Or possibly if there are other errors:
if (null == someObj) { throw new RuntimeException(); }
Is this an approach you use?
Pseudo Code:
public class SomeWorkerObject {
private String field1 = "";
private String field2 = "";
public setField1() { }
public setField2() { }
// Do I throw runtime exception here?
public execute1() {
try {
// Do something with field 1
// Do something with field 2
} catch(SomeException) {
throw new RuntimeException();
}
}
// Do I throw runtime exception here?
public execute2() {
try {
// Do something with field 1
// Do something with field 2
} catch(SomeException) {
throw new RuntimeException();
}
}
}
public class TheWeb {
public void processWebRequest() {
SomeWorkerObject obj = new SomeWorkerObject();
obj.setField1("something");
obj.setField2("something");
obj.execute1();
obj.execute2();
// Possibility that runtime exception thrown?
doSomethingWith(obj);
}
}
I have a couple of problems with this code. There are times when I don't want a runtimeexception to be thrown because then execution stops in the calling method. It seems if I trap the errors in the method, maybe I can continue. But I will know if I can continue later on the program.
In the example above, what if obj.execute1() throws a Runtimeexception, then the code exits?
Edited: This guy seems to answer a lot of my questions, but I still want to hear your opinions.
http://misko.hevery.com/2009/09/16/checked-exceptions-i-love-you-but-you-have-to-go/
"Checked exceptions force me to write catch blocks which are meaningless: more code, harder to read, and higher chance that I will mess up the rethrow logic and eat the exception."
When catching an exception and throwing RuntimeException instead, it is important to set the original exception as a cause for the RuntimeException. i.e.
throw new RuntimeException(originalException).
Otherwise you will not know what was the problem in the first place.
Rethrowing checked exceptions as unchecked exceptions should only be done if you are sure that the checked exception is not to be expected.
Here's a typical example:
try {
hash = MessageDigest.getInstance("MD5").digest(string.getBytes("UTF-8"));
} catch (NoSuchAlgorithmException e) {
// Unexpected exception. "MD5" is just hardcoded and supported.
throw new RuntimeException("MD5 should be supported?", e);
} catch (UnsupportedEncodingException e) {
// Unexpected exception. "UTF-8" is just hardcoded and supported.
throw new RuntimeException("UTF-8 should be supported?", e);
}
There are times when I don't want a
runtimeexception to be thrown because
then execution stops in the calling
method. It seems if I trap the errors
in the method, maybe I can continue.
But I will know if I can continue
later on the program.
You have the right idea. The advice about throwing RuntimeException is that it doesn't require the caller to use a try-block or a 'throws' clause.
If your code can recover from an exception than it really should catch it and not throw anything.
One of the first rules about exceptions is to not abuse them to pass state in your application. They should be used for exceptional situations, not as alternative return values.
The second rule is to catch exceptions at the level you process them. Catch and rethrow does not add much. Any cleanup code in your method should be done in a finally block.
In my opinion catching checked exceptions and rethrowing them as runtime exceptions is abusing the system. It feels like working around the "limitations" of design by contract instead of using those "limitations" to get a more robust application.
Whether or not to handle an exception or simply rethrow it depends on your use case.
For example, if you're reading a file to load data into your application, and some IO error occurs, you're unlikely to recover from the error, so rethrowing the error to the top and consequently terminating the application isn't a bad course of action.
Conversely, if you're anticipating recoverable errors then you should absolutely catch and handle the errors. For example, you may have users entering data in a form. If they enter data incorrectly, your input processing code may throw an exception (e.g. NumberFormatException when parsing a malformed number string). Your code should catch these exceptions and return an error the user, prompting for correct input.
On an additional note, it's probably bad form to wrap all your exceptions with RuntimeException. If your code is going to be reused somewhere else, it is very helpful to have checked exceptions to signify that your code can fail in certain ways.
For example, assume your code is to parse configuration data from a file. Obviously, an IO error may occur, so you will have to catch an IOException somewhere in your code. You probably won't be able to do anything about the error, so you will have to rethrow it. However, someone calling into your code may well be able to handle such an error, for example by backing off to configuration defaults if the configuration can't be loaded from the file. By marking your API with checked exceptions, someone using your code can clearly see where an error may occur, and can thus write the error handling code at the appropriate place. If instead you simply throw a RuntimeException, the developer using your code won't be aware of possible errors until they creep up during testing.

Categories

Resources