Im am currently developing an automated "test" class (running several individual tests on other classes in the same package). The aim of the test file is to show whether each test either passed or failed. Some of the files being tested are not written correctly creating an ArrayOutOfBoundsException when running the test, that produces my test file to crash and not carry on until the end performing other tests. I am not in the position to modify code to fix the errors on the project being tested.
-> how to stop an exception from halting program execution in Java without creating any new classes
Thank for all your help, advice and sharing.
Best way to stop it happening: fix the code to perform appropriate checking.
If you can't fix the code which is actually failing, you could catch the exception explicitly at an "outer" level, log a warning and continue with the next file:
try
{
operationWhichMightThrow();
}
catch (ArrayIndexOutOfBoundsException e)
{
log.warning("Failed file " + filename, e);
// Do whatever you need to continue to the next file.
}
Catch the exception and log it as a test failure.
Related
I am trying to understand which call causes Error and Which causes failures in Junit4. Until Junit3,
Failure can be created using
junit.framework.AssertionFailedError
And Error with
junit.framework.Assert.assertEquals
But with the deprecation of junit.framework.Assert, which is not moved to org.junit.Assert, I am not able to find a way in junit4 to throw a failure. Anything I try with org.junit.Assert (even Assert.fail() ) , JUnit considers it as Error.
Any idea on how to properly generate failures in Junit4 style tests?
Update
I figured out that there is a std.err at the end of XML generated by JUnit ant target.
<system-err>TEXT here</system-err>
and I suspected this is the cause that making it ERROR instead of Failure. But when I cleared all sys.err, it still marking it ERROR.
You can still use Assert.assertThat for getting assertion failure
assertThat(0, is(1)); // fails:
assertThat(0, is(not(1))) // passes
It may not what you need, but also JUnit 4 has ComparisonFailure
Thrown when an assertEquals(String, String) fails. Create and throw a ComparisonFailure manually if you want to show users the difference between two complex strings.
I am having the same issue. The only solution I have found so far is to use a try block followed by
catch (AssertionError ae) {
fail(ae.toString());
}
But I can see downsides to this and I have seen many people say this is bad practice. Unfortunately I don't see another way around it when using ant to make a report.
I have a problem with Eclipse and one of my apps. Eclipse ONLY hits breakpoints when I throw an exception but not when it runs other lines of code "normally".
I am running the project in
C:\.....SmashDataServiceExternal\processor\bin
While my source code is under a different directory:
C:\.......\SmashDataProcessorExternal\...
When I try to run my app, it does not hit any of lines of code normally, but if I break on an Exception and I make my App throw an exception, then Eclipse breaks on the correct line in the correct source file.
i.e:
System.out.println("HISTORIC DATA: " + historicData.getDatasetId());
System.out.println("HISTORIC DATA TYPE: " + historicData.getReplayEventTypeId());
outputInputRequest(outputEvent);
logger.info("Sent BatchJobRequest for batchId {}, sessionId {} for byTime request", outputEvent.getBatchId(batchIdFlyweight), outputEvent.getSessionId(sessionIdFlyweight) );
if (1==1) {
throw new NullPointerException();
}
I set break point on every single line above, my app actually prints out the statements but does not break until nullpointer gets thrown.
https://imgur.com/a/8f306
I would appreciate any advise on how to get Eclipse to break properly.
Thank you.
I have an Applet whose method gets called from a JavaScript function within a browser. This method will eventually send a file to an Amazon S3 bucket. When this method attempts to create the AmazonS3Client however, the method fails without displaying any errors.
The relevant snippet of the code within the method is:
InputStream input = DigitalLive.class.getResourceAsStream("AwsCredentials.properties");
System.out.println("File loaded into Input Stream.");
PropertiesCredentials theCredentials = new PropertiesCredentials(input);
System.out.println("Credentials created.");
System.out.println("AccessKey is:" + theCredentials.getAWSAccessKeyId());
System.out.println("SecretKey is:" + theCredentials.getAWSSecretKey());
//All of the above strings print to the console with the correct AccessKey and SecretKey
try{
AmazonS3 s3Client = new AmazonS3Client(theCredentials);
//This message never prints
System.out.println("Client created.");
} catch(Exception e) {
//This message never prints
System.err.println("Error creating AmazonClient: " + e.getMessage());
}
None of the messages within the try/catch block ever print. None of the rest of the method's code (not shown here for brevity) gets fired either.
The jar file compiles without error. I'm using jdk 1.7.0_51 and the amazon aws-java-sdk-1.7.1. I'm using Eclipse as the IDE and am building the jar with a build file using ANT.
I'm not really sure what else to try other than wrapping the code in a try/catch block.
Is there a different/better way for me to debug the Java code to learn why the AmazonS3Client is not created? Or perhaps a more obvious reason why it might fail given the code snippet above?
EDIT: I added a try/catch block in the JavaScript code that calls the Java method and it throws an error:
Error calling method on NPObject
Error: java.lang.reflect.InvocationTargetException
I think what this tells me that the Java Applet is in fact throwing an error. I'm just not sure how to figure out which one and how to solve it. I've attempted to put try/catch blocks around the AmazonS3 s3Client = new AmazonS3Client(theCredentials); but the IDE tells me Unreachable catch block for InvocationTargetException. This exception is never thrown from the try statement body.
As it turns out, the error message was not being written to the console when the method in question was called from within JavaScript. I modified the Applet so that the method could be called from within the Applet, and the error was displayed in the console as expected.
The Applet was missing an Apache class, so that was added and all is well.
Can anyone help me with my problem?
I test my program with Robotium in Junit.
My problem is:
When I detect there is a failure in junit, how can I use code to detect there is failure in program? So, I can continue run if no error occur? e.g. if no error, continue testing, else exit.
I suggest using Java's built-in assertions for your test. To create an assertion:
assert someBoolean : message;
For example:
assert (myValue == 3) : "myValue was " + myValue + ", should have been 3";
Assertions are disabled by default when running your program. To run your program with assertions, run it like this:
java -enableassertions MyClass
Then, if your program is running with this runtime option, whenever an assert is reached, the following happens:
If the boolean is true, the program will continue.
If it is false, an AssertionError is thrown with the specified message.
For example:
int myVar = 5;
assert (myVar == 3) : "myVar is " + myVar + " not 3";
results in
Exception in thread "main" java.lang.AssertionError: myVar is 5 not 3
IF assertions are enabled. Remember: all of that only happens when you enable asserts using -enableassertions or -ea. If you don't, the asserts are skipped.
When I detect there is a failure in junit, how can I use code to detect there is failure in program? So, I can continue run if no error occur? e.g. if no error, continue testing, else exit.
This doesn't make much sense. If you've got a failure in a JUnit test, that means there is a failure in your program. If no failure occurs, the unit testing will proceed to the next test automatically.
But maybe you are asking if you can do this:
// in some unit test
assert(....); // <<--- this test fails:
// Do something so that the unit test will continue to the next assertion ...
assert(....)
The answer is that you can't do that in any useful way:
The unit test framework can only report unit test failures that indicate that they have failed by terminating with an exception.
You could write a unit test to catch the exception that an assert(...) or fail(...) call throws and continue to the next assertion. But that would destroy all evidence of the previous unit test failure.
So if you want to be able to do the second assertion despite the first one failing, you need to make them separate testcases.
You might also be asking if there is a way to get the JUnit test runner to abort on the first failed unit test. The answer is yes that it is possible, but how you would do it would depend on the test runner you are using.
You can make assertions for a condition to be true or false-
assertTrue(soloObject.waitForActivity("Activity Name"));
Instead of wating for an activity you can use all the methods provided by robotium to make assertions example isTextFound("text"), isTextFound("text"), isCheckBoxChecked(index), etc.
I had a strange problem today... I'm going to make a simplified example since it "worth a thousands words" :D
public class Application() {
public static void main(String[] args) {
try {
A a = new A(); // this may throw exceptions
// (which will cause an ExceptionInInitializerError)
} catch (Throwable t) {
JOptionPane.showMessageDialog(null, "Oooops!");
System.exit(1);
}
}
}
Since it's a stand-alone application with a Swing GUI, my goal is to give a message to the user in case of any problems (in this case at startup)... the code above works in Eclipse IDE but when I export the project as executable jar by double-clicking on it, well, it just won't open.
So I try to execute it in cmd with java -jar application.jar and it prints in the shell that there was an ExceptionInInitializerError.
Why the error was not caught?
It doesn't work even if I specify catch (ExceptionInInitializerError e).
EDIT:
After more indepth debugging, I found out that this problem only happens when two particular exceptions occur and the latter occurs in the catch block of the former.
I corrected the bug by changing the order of some checks that I do on startup.
The problem btw should never happen since it was originated by a volountary mistake of the JDBC driver class name to load in a static block.
Well, at least it made me clearly understand why constructors and static initialization blocks should not throw exceptions: it makes debugging almost impossible in the case in which the class that throws the exception is used by many classes, since it may become very hard to find out when the class is loaded.
I can think of three possible explanations for an ExceptionInInitializerError not being caught in your example:
It could be being thrown by JOptionPane.showMessageDialog(null, "Oooops!");
It could be thrown before main is called.
It could be thrown on a different stack.
In fact, I think that the 2nd one is the most likely, as ExceptionInInitializerError is thrown when some unchecked exception is thrown (and not caught) during the initialization of a class. That could well be happening before you enter the try block.