Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mock nested methods in Java

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!

like image 380
Felix Avatar asked Jun 18 '26 16:06

Felix


1 Answers

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);
like image 118
SungJin Steve Yoo Avatar answered Jun 21 '26 06:06

SungJin Steve Yoo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!