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!

Maciej Kowalski
  • 25,605
  • 12
  • 54
  • 63
Felix
  • 95
  • 2
  • 11

2 Answers2

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

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

LenglBoy
  • 1,451
  • 1
  • 10
  • 24