1

I am having a problem on my query object, it becomes null even though I stub it with a query mock object.. This is the code

Query query = getEntityManager().createNativeQuery(queryString, SomeRandom.class); return query.getResultList(); //-->This is where I get the error, the query object is null. 

my Test method is

Query query = mock(Query.class); when(entityManager.createNativeQuery("", SomeRandom.class)).thenReturn(query); List<SomeRandom> someList = requestDao.getSomeList(parameter, parameter, parameter, parameter); 
2
  • Have you tried anyString() instead of empty string ("") when mocking the createNativeQuery function? Commented Sep 2, 2015 at 3:25
  • yes I did, but I already solved the problem. Thanks btw. Commented Sep 2, 2015 at 6:42

2 Answers 2

3

This probably means that one of the matchers that you passed to the mocked method did not match. You passed an actual String instance (the empty string), which is transformed under the hood into an Equals matcher. Your example would only work if queryString was the empty string as well.

This should match on any query string:

when(entityManager.createNativeQuery(anyString(), eq(SomeRandom.class))) .thenReturn(query); 

And this on some concrete String that you expect to be passed:

String expectedQueryString = "select 1"; when(entityManager.createNativeQuery(expectedQueryString, SomeRandom.class)) .thenReturn(query); 

Edit based on comment:

If changing from eq(SomeRandom.class) to any() solved the problem, then the eq(SomeRandom.class) matcher did not match, which means SomeRandom.class was not what was in fact passed to the mocked method.

Sign up to request clarification or add additional context in comments.

1 Comment

It didn't work for me, I already did that thing before posting this question. I got the answer from this github.com/spring-projects/spring-data-jpa/blob/master/src/test/…
1

I was able to do it with this code, I used This as my reference.

Class<?> type = Mockito.any(); when(entityManager.createNativeQuery(Mockito.anyString(), type)).thenReturn(query); 

2 Comments

Never extract Mockito matchers to local variables. Matchers work via side-effects, and extracting like you have here gets them misaligned. This code works for now (as any doesn't check anything about the parameter) but this will break in hard-to-diagnose ways if you change either matcher to eq or anything else.
Thanks, I'm gonna check it out.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.