I have a class with couple of methods and each with a try catch block to look for any exceptions.
The code as follows:
public ResponseEntity get() {
try {
.....
} catch (Exception e) {
output = new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
}
return output;
}
and I came up with a test case using Mokito to test the above scenario but confused how to enter into catch block of the above
#Test
public void testgetAllUsers_withoutexecp() {
when(sMock.getAll()).thenReturn(someList);
Assert.assertTrue(result.getStatusCode() == HttpStatus.OK );
}
#Test(expected=NullPointerException.class)
public void testgetAllUsers_execp() {
when(sMock.getAll()).thenReturn(null);
Assert.assertFalse(result.getStatusCode() == HttpStatus.OK );
}
I tried to raise a NullPointerException but still the catch block is left out in codecoverage (by which I assume it is not been tested). please help me to write a Junit test case for this to enter exception. I am very new to all these topics.
You can raise exception using thenThrow clause of Mockito:
when(serviceMock.getAllUser()).thenThrow(new NullPointerException("Error occurred"));
and then assert like this:
Assert.assertTrue(result.getStatusCode() == HttpStatus.INTERNAL_SERVER_ERROR);
Expecting NullPointerException makes no sense. This will never happen, because you catch exceptions.
Instead, test for AppConstants.ERROR_MESSAGE9
and HttpStatus.INTERNAL_SERVER_ERROR
Related
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(...));
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.
This question already has answers here:
JUnit right way of test expected exceptions
(4 answers)
Closed 5 years ago.
I would like to know how I can write a unit test to get the catch block covered for the following method. The FOM.create(data) is a static method.
public String getValue(Data data) {
try {
return FOM.create(data);
} catch (UnsupportedEncodingException e) {
log.error("An error occured while creating data", e);
throw new IllegalStateException(e);
}
}
Currently this is my unit test but it doesn't hit the catch block:
#Test (expected = UnsupportedEncodingException.class)
public void shouldThrowUnsupportedEncodingException() {
doThrow(UnsupportedEncodingException.class).when(dataService).getUpdatedJWTToken(any(Data.class));
try {
dataService.getValue(data);
}catch (IllegalStateException e) {
verify(log).error(eq("An error occured while creating data"), any(UnsupportedEncodingException.class));
throw e;
}
}
You can check throwable exception if exception does not caught before unit test. In your case you cant check UnsupportedEncodingException but can check IllegalStateException.
Unit test must looks like:
#Test (expected = IllegalStateException.class)
public void shouldThrowIllegalStateException() {
dataService.getValue(data);
}
if you wanna to check UnsupportedEncodingException you must testing FOM.create(data) method
You can use JUnits exception rule like this:
public class SimpleExpectedExceptionTest {
#Rule
public ExpectedException thrown= ExpectedException.none();
#Test
public void throwsExceptionWithSpecificType() {
thrown.expect(NullPointerException.class);
thrown.expectMessage("Substring in Exception message");
throw new NullPointerException();
}
}
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 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);