I am doing Android Unit Test Case Execution and for Negative Test Case I should get exception, but for some API's Exception is not caught.
Please do find the example below:
public void testInsertSenderType_n() {
DBSms obj = new DBSms(getContext());
obj.open();
int i =0;
int a =0;
boolean result = true;
i=obj.GetToatlCount();
obj.insertSmsText(i+1,"Hello to testInsertSenderType_n");
a=obj.TotalcountSms("Inbox");
try
{
obj.insertSenderType(-100, "Richard", "Inbox", 0);
}
catch (Exception e)
{
// TODO: handle exception
result = false;
}
assertEquals(a,obj.TotalcountSms("Inbox"));
assertEquals(false,result);
obj.close();
}
Here in, obj.insertSenderType(-100, "Richard", "Inbox", 0); should throw an exception. But it is not thrown.
Please do guide where can I be Wrong.
I use following method to expect proper exception:
try {
doSomethingToProvokeException();
fail("there ought to be an exception dude, but was not");
} catch(ExeptionIHaveProvoked ex) {
doAssertionnsonThrowsException
}
You do not need variables to keeps exception state. As for why no exception is thrown in your code - nobody cann tell it to you, unless you provide source of object.
Related
I am quite new to Java and I am struggeling to understand Exceptions.
In an Excercise I was supposed to implement the Interface "exceptions.excercise.Validator" in the class "ValidatorImpl" and the Method "User#validate".
I am struggeling to understand what exactly is happening in these lines of codes and I would really appreciate it, if somebody could help me :):
I am not sure if you need the whole java project to understand the code but here's what I don't really understand:
*In User.java
public void validate() throws UserException {
Validator valid = new ValidatorImpl();
try {
valid.validateAge(this.getAge());
valid.validateEmailWithRuntimeException(this.getEmail());
} catch (ValidationException e) {
throw new UserException("age is incorrect", e);
} catch(ValidationRuntimeException e ) {
throw new UserException("mail is incorrect", e);
}
}
In ValidatorImpl.java:
package exceptions.excercise;
public class ValidatorImpl implements Validator {
#Override
public void validateAge(int age) throws ValidationException {
if ((age < 0) || (age > 120)) {
throw new ValidationException(age + "not betweeon 0 and 120");
}
}
#Override
public void validateEmailWithRuntimeException(String email) {
if (email == null) {
throw new ValidationRuntimeException("email is null");
}
if (!email.contains("#")) {
throw new ValidationRuntimeException("email must contain #sign");
}
}
}
I know this is quite a lot.
Thank you if you read all of this :)
First, you have a try-catch block. This will catch exceptions thrown in the try-part and if an exception is found they'll run the catch-block for the type of exception. The methods valid.validateAge(int) and valid.validateEmailWithRuntimeException(String) both can throw exceptions.
If the age is under 0 or over 120 validateAge will throw an ValidationException. The try-catch will catch that and will run the first catch-block, which will output a new UserExeption("age is incorrect").
If the age is valid, validateEmailWithRuntimeException will be called next.
This works the same way! If the Email is invalid, a ValidationRuntimeException will be thrown and catched. In this case, the second catch-block will be called and a new UserExeption("mail is incorrect") will be outputted.
I have the following java code :
public void someMethod(){
try{
// some code which generates Exception
}catch(Exception ex1) {
try{
// The code inside this method can also throw some Exception
myRollBackMethodForUndoingSomeChanges();
}catch(Exception ex2){
// I want to add inside `ex2` the history of `ex1` too
// Surely , I cannot set cause of `ex2` as `ex1` as `ex2`
// can be caused by it's own reasons.
// I dont want `ex1` details to be lost if I just throw `ex2` from my method
}
}
}
How to do it ?
EDIT : Actually this happens in my service layer and I have controller advice for logging. Hence I don't want to add 2 loggers here.
You can add ex1 to the supressed exceptions in ex2 via the method addSuppressed before rethrowing it.
Quick code example:
public static void main(final String[] args) {
try {
throw new IllegalArgumentException("Illegal Argument 1!");
} catch (final RuntimeException ex1) {
try {
throw new IllegalStateException("Illegal State 2!");
} catch (final RuntimeException ex2) {
ex2.addSuppressed(ex1);
throw ex2;
}
}
}
will produce the exception output:
Exception in thread "main" java.lang.IllegalStateException: Illegal State 2!
at package.main(Main.java:26)
Suppressed: java.lang.IllegalArgumentException: Illegal Argument 1!
at package.main(Main.java:20)
I am writing a test case using JUnit and I am trying to catch an Exception using #Test(expected=Exception.Class). For some reason I am unable to catch the exception. If I pass null it would throw NullPointerException and the test catches it because Exception is the parent class but on my Coverage report the exception is still not covered.
Method under test:
private static final String CONTENT_LENGTH = "Content-Length";
protected long getContentLength( MultivaluedMap<String, String> headers ) {
String length = headers.getFirst( CONTENT_LENGTH );
if( length != null ) {
try {
return Long.valueOf( length );
} catch( Exception e ) {}
}
return 0;
}
JUnit test case:
#Test(expected=Exception.class)
public void testGetContentLength() {
new TestBaseMessageBodyReader().getContentLength(null);
}
Any help would be appreciated.
Thanks
Catching generic exception is bad practice and even worse to catch an exception and do nothing. in your try catch you should catch NumberFormatException which is what Long.valueOf has the potential of throwing. Even then your jUnit will not never catch the exception because you are catching the exception but not doing anything with it, the method would always return 0 as it's currently written (provided you're not passing null)
Here is some code that would catch the exception on your unit test. I'd create two unit tests, one to catch your the first exception and one to catch the second.
protected long getContentLength(MultivaluedMap<String, String> headers)
{
if(null == headers)
{
throw new SomeCustomException("some message");
}
Long returnValue = 0;
String length = headers.getFirst(CONTENT_LENGTH);
try
{
returnValue = Long.valueOf(length);
}
catch (NumberFormatException e) {
// if you can recover handle it here
// if you can't recover then break the app
throw new SomeOtherCustomException("some other message");
}
return returnValue;
}
I am calling a method from a third party jars whose class file is not accessible to me. So for some cases it throws exception logs and I want to extract string from the current log dynamically.
This is the java program method which throws exception
public String runLayoutTest(final String xmlFile){
try{
String gettingValue = "novalue";
boolean errorFlag = perform("runLayoutTest", new Reporter.Reportable() {
#Override
public boolean run() throws Exception {
String layoutXml = null;
//current directory
Path currentRelativePath = Paths.get("");
String currentProjectPath = currentRelativePath.toAbsolutePath().toString();
System.out.println("Current relative path is: " + currentProjectPath);
System.out.println("layoutXml "+xmlFile);
String x = client.runLayoutTest(currentProjectPath+"\\Excel\\"+xmlFile);
System.out.println("******* x ********"+x);
setX(x);
return true;
}
});
gettingValue = getX();
return gettingValue;
}catch(Exception e){
System.out.println("**Any one rule in Layout is failed**");
//System.out.println(e.getMessage());
return getX();
}
}
Here the client is a object of the third party jar file , And that is throwing me the exception on some odd cases .
The Exception logs are
com.experitest.client.InternalException: Exception caught while executing runLayoutTest: {"rule_1":{"Exists":true},"rule_2":{"Exists":true,"EqualHeight":false},"rule_3":{"AlignedLeft":false}}
at com.experitest.client.JavaClientInternals.executeInternally(JavaClientInternals.java:234)
at com.experitest.client.Client.execute(Client.java:237)
at com.experitest.client.Client.runLayoutTest(Client.java:1475)
at com.igate.framework.NativeDriver$79.run(NativeDriver.java:2753)
at com.igate.framework.Reporter.action(Reporter.java:81)........
From this exception I want to extract
runLayoutTest: {"rule_1":{"Exists":true},"rule_2":{"Exists":true,"EqualHeight":false},"rule_3":{"AlignedLeft":false}}
as a String.
Hence is there any method with which I can dynamically extract such String whenever it occurs.
And I still don't know the reason why my catch method is not getting called.
In your case you can just use Exception.getMessage() which will result in
Exception caught while executing runLayoutTest:
{"rule_1":{"Exists":true},"rule_2":{"Exists":true,"EqualHeight":false},"rule_3":{"AlignedLeft":false}}
Below can be used to get the json string. You can then parse the json to get desired data from it
String message = e.getMessage();
int colonIndex = message.indexOf(":");
String json = null;
if (colonIndex != -1) {
json = message.substring(colonIndex + 1);
}
Please note that this solution will not work in case of wrapped exception
I had to implement this code to attack directly to throwable detailMessage. I had to ignore all the hierarchy of classes that extended Exception because someone implemented a horrible getMessage method that was being overlapped with web components. In JUnit was no way to define unit test cases because framework's exceptions always tried to translate its error code into the 'session' (web) language...
public static Object getThrowableDetailMessage(Throwable throwable) {
try {
// Tiramos la puerta abajo y pedimos a Throwable que nos pase el código de error
Field f = Throwable.class.getDeclaredField("detailMessage");
f.setAccessible(true);
Object detailMessageFound = f.get(throwable);
return detailMessageFound;
} catch (SecurityException ex) {
//LOG
return null;
} catch (NoSuchFieldException e) {
//LOG
return null;
} catch (IllegalArgumentException e) {
//LOG
return null;
} catch (IllegalAccessException e) {
//LOG
return null;
}
}
You also can try to replace Throwable by InternalException and keep the reflection on this level of the hierachy. But like someone is already pointing. Make sure your code is being affected by the Exception you want to inspect.
I have implemented all the catches possible because I wanted to trace a different log for everyone of them. (For debugging and testing overall)
Note: My code has been implemented under JDK 1.6_18
How can I make my Java run again from the start (main) when it encounters an exception without closing and running it again manually?
My program basically writes on a file. When it cannot find the file I will throw the FileNotFoundException then write the file (say for example hello.txt). After it writes, the program closes (in NetBeans cause I am still developing it) and start showing this at the buttom:
Exception in thread "main" java.lang.NumberFormatException: null
at java.lang.Integer.parseInt(Integer.java:542)
at java.lang.Integer.parseInt(Integer.java:615)
at app4pics1word.App4pics1word.cache(App4pics1word.java:127)
at app4pics1word.App4pics1word.<init>(App4pics1word.java:18)
at app4pics1word.App4pics1word.main(App4pics1word.java:146)
Java Result: 1
you can try this
public static void main(String[] args) {
try {
//something wrong happens here
}catch(Throwable e) {
e.printStackTrace();
main(args);
}
}
You should use exception handling instead of restarting the program. If you restart the program, the error will still be there and thus your program will keep on trying to run for eternity, always failing with the same exception.
You would like to catch your exception and make sure that the input is valid:
boolean okInput = false;
int x = -1;
String someData = "rr";
do {
try {
x = Integer.parseInt(someData); // try to parse
okInput = true;
} catch(NumberFormatException n) {
// Error, try again
okInput = false
someData = "2";
}
} while(!okInput); // Keep trying while input is not valid
// Here x is a valid number
This tutorial provides you good code in general of how exceptions work.
is this what you are looking for ?
public static void main(String [] args) {
boolean done = false;
do {
try {
writeSomeFile();
done = true;
}
catch (Exception ex)
{
System.out.println("Exception trapped "+ex)
}
} while (!done);
}
You can make it a loop that is broken only when the try block succeeds without an Exception:
public static void main(String[] args) {
while(true) {
try {
...
break; //at the end of try block
}
catch (SomeException e) {
//print error message here, or do whatever
}
}
//program continues here once try block gets through w/o exceptions
...
}
However, instead of having this in your main I recommend hiding this rather ugly structure inside a method.