Mocking a function without argument containing CriteriaBuilder is it possible?

Viewed 10

I think the reason why is impossible to mock criteriabuilder is because it only response to the database created in postgres. If that's not the case then how can solve this error (shown below). class MessageRest

 public List<Message> getListAll(){
        logger.info("Get all messages");
        return messageRepository.getAll();
    }

class MessageRepository

 public List<Message> getAll(){
        CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
        CriteriaQuery<Message> criteria = criteriaBuilder.createQuery(Message.class);
        criteria.from(Message.class);
        return entityManager.createQuery(criteria).getResultList();
    }

class MessageRestTest

class MessageRESTTest {


    @InjectMocks
    MessageREST messageREST;

    @Mock
    private EntityManager entityManager;
    @Mock
    private MessageRepository messageRepository;

    @BeforeEach
    void Mockactivator() {
        MockitoAnnotations.initMocks(this);
    }

 @Test
    void testgetlistall()
    {

        List<Message> messageList = new ArrayList<>();
        Message message = new Message();
        messageList.add(message);
        when(messageRepository.getAll()).thenReturn(messageList);
        messageList = messageREST.getListAll(); 
    }
}

The Error am getting is NullpointerException and it's comming from the last line "messageList = messageREST.getListAll()" Thanks in advance!

1 Answers

It might not what you are looking for, but just in case:

Usually for such repository tests in memory databases are used, for example H2. So you can fill it with test data and then call getAll() to check if it works correctly.

Related