EasyMock to test SecurityException - java

I am trying to use easyMock to write a test, that tests SecurityException in the following code.
eg. for NumberFormatException I use the below.
EasyMock.expect(mockEntityManager.find(UserProfile.class,"abc")).andThrow(new
NumberFormatException());
Any ideas on what to expect to throw SecurityException?
public Object getAsObject(FacesContext facesContext, UIComponent
uiComponent, String s) {
EntityManager entityManager = (EntityManager)Component.getInstance("entityManager");
if (s == null || s.equals("null")) {
return null; } else {
try {
long i = Long.parseLong(s);
return entityManager.find(UserProfile.class, i);
} catch (NumberFormatException e) {
logger.error(e);
} catch (SecurityException e) {
logger.error(e);
} }
return null; }

I have the feeling that you haven't written that code, and that's why you're wondering what might throw SecurityException. The answer is nothing, as long as you're using a good implementation of EntityManager.
The documented version of EntityManager.find()enter link description here doesn't throw SecurityException. BUT if you're running that code inside a J2EE app server that uses a custom version of EntityManager, it could be that it throws that exception... But I don't think it should.

Thanks for your responses..here is what I did to expect SecurityException.
MyClass abc = new MyClass();
EasyMock.expect(mockEntityManager.find(MyClass.class,111L)).andThrow(new SecurityException());
EasyMock.replay(mockEntityManager);
Object target = abc.getAsObject(mockFacesContext, mockUiComponent,"111");
Assert.assertEquals(null, target);

Related

How to unit test the catch exception statement?

How do I test the catch statement below? My coverlay is failing and I am not sure how to cover this line.
public Method execute(#NonNull final String test) throws ServiceException {
try {
object = javaClient.fetchInfo(test);
} catch (ClientException | InternalServerError e) {
throw serviceExceptionAdapter.apply(e);
}
return object;
}
This is currently what I have in my test file:
#BeforeEach
void setup() {
this.serviceExceptionAdapter = mock(ExceptionAdapter.class);
this.mockJavaClient = mock(JavaClient.class);
proxy = new Proxy(mockJavaClient, serviceExceptionAdapter);
}
#Test
void test_InternalServerError() {
when(mockJavaClient.fetchInfo(any())).thenThrow(InternalServerError.class);
when(serviceExceptionAdapter.apply(any())).thenThrow(ServiceException.class);
assertThrows(ServiceException.class, () -> proxy.execute(test));
verify(serviceExceptionAdapter, times(1)).apply(any());
}
I have to guess a little bit, as you didn't provide a full working example. From what I see in your catch block
} catch (ClientException | InternalServerError e) {
throw serviceExceptionAdapter.apply(e);
}
you expect the return value of your .apply(e) function to be an exception and throw that exception. In your test however, your mocked serviceExceptionAdapter doesn't return an Exception, but throws one instead:
when(serviceExceptionAdapter.apply(any()))
.thenThrow(ServiceException.class);
If my interpretations are correct, your code should work if you change the mentioned line in the test to the following:
when(serviceExceptionAdapter.apply(any()))
.thenReturn(new ServiceException(...));

How to catch HystrixTimeout Exception in Zuul

when web service does not respond in a time(timeout) and throwing HystrixTimeout Exception, i want to catch HystrixTimeout Exception in ZuulFilter. how can i handle that?
Note: in ZuulFilter, i catch my custom exception. Like a below code
#Override
public Object run() {
final RequestContext context = RequestContext.getCurrentContext();
final Object throwable = context.get(THROWABLE_KEY);
if (throwable instanceof ZuulException) {
ZuulException zuulException = (ZuulException) throwable;
}
return null;
}
this problem was not my real problem. firstly, i understood this. Because my app throwing SocketTimeoutException as a base exceptio. So if i can catch SocketTimeoutException, i can handle this problem but for this solution i need to get exceptions' cause of cause. I wrote a method like a below code.
private Throwable findRightException(Throwable th) {
Throwable throwable = th;
if (throwable.getCause() == null || throwable.getCause() instanceof SocketTimeoutException) {
return throwable.getCause();
}
return findRightException(throwable.getCause());

How does Validation.Exception in Java work?

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.

Catching Exception with JUnit #Test(expected=Exception.Class)

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 want to extract a string from the current exception thrown in a java program

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

Categories