How to create a stub for BusinessException which extends Exception class

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);

BusinessException extends Exception

Testable class

public class FacadeBean{
        }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.


Resolved in the comments:

Why are you mocking an Exception? Why wouldn’t a real BusinessException work?


Why do you use thenThrow(BusinessException.class) instead of thenThrow(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.

Leave a Reply

Your email address will not be published. Required fields are marked *