3

In order to test my program I need to mock a method call like:

entityManager.createQuery("SELECT...", Integer.class).getSingleResult()

the createQuery part returns a TypedQuery<Integer>, but I actually just want to return a single integer: 1. Currently I am using Mockito in order to create my mocks and I am pretty new to this.

Is there a way of testing this?

Thank you!

3
  • 1
    Mock a result, which mocks the result. Commented Oct 18, 2017 at 7:39
  • Yes. That's it. Thank you! I thought too complicated on that one. Commented Oct 18, 2017 at 7:45
  • Possible duplicate of mock nested method calls using mockito Commented Aug 29, 2018 at 13:15

2 Answers 2

4

Assuming you have class EntityManager, Query. You can mock your test like below. (mock(), any(), when() ... methods are in Mockito)

int result = 1;
Query query = mock(Query.class);
EntityManager entityManager = mock(EntityManager.class);

when(entityManager.createQuery(any(), any()).thenReturn(query);
when(query.getSingleResult()).thenReturn(result);
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. Worked for me
0

Mock the EntityManager and then you can pre-define the returning-value. Mockito.doReturn(1).when(entityManagerMock).createQuery(any(String.class), any());

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.