I am trying to create stub for the exception class to return some string , but its not returning that string value.Got error
java.lang.Exception: Unexpected exception, expected<ServiceException> but was<java.lang.NullPointerException>
Here is sample code I use
BusinessException mockBusinessException =mock(BusinessException.class); @Test(expected = ServiceException.class) public void testValidateForRegistrationError() throws ServiceException, BusinessException{ when(ChecksUtil.initiateValidation(any(Request.class), any(Content.class))).thenThrow(BusinessException.class); when(mockBusinessException.getMessage()).thenReturn("Error"); facadeBeanTest.createRegistration(RegistrationFacadeMock.getCreateRegistrationRequest()); } BusinessException extends Exception
Testable class
public class FacadeBean{ createRegistration(){ try{ }catch (BusinessException e) { String err = e.getMessage(); -- Failed in this line(null pointer exception) if(err.contains("Error") ){ throw new ServiceException(ServiceErrorConstants.CATALOG_NAME, err); } } } }
Is there any thing missing in that ?could some one suggest.
Answer
Resolved in the comments:
Why are you mocking an Exception? Why wouldn’t a real BusinessException work?
and
Why do you use
thenThrow(BusinessException.class)
instead ofthenThrow(mockBusinessException)
?
Comment from OP, user3123934:
its resolved after doing like this when(ChecksUtil.initiateValidation(any(Request.class), any(Content.class))).thenThrow(new BusinessException(“Error”));
When there are few dependencies and a reliable implementation, it often makes sense to use real objects instead of mocks. If you do use mocks, ensure that your system under test will use the mock instances when necessary, by supplying them in a constructor, mock, or overridden method.