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);
Aaron
  • 2,591
  • 4
  • 27
  • 45

2 Answers2

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.

Henning
  • 16,063
  • 3
  • 51
  • 65
  • It didn't work for me, I already did that thing before posting this question. I got the answer from this https://github.com/spring-projects/spring-data-jpa/blob/master/src/test/java/org/springframework/data/jpa/repository/query/SimpleJpaQueryUnitTests.java – Aaron Sep 02 '15 at 06:45
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);
Aaron
  • 2,591
  • 4
  • 27
  • 45
  • **Never extract Mockito matchers to local variables.** [Matchers work via side-effects](http://stackoverflow.com/q/22822512/1426891), 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. – Jeff Bowman Sep 02 '15 at 22:55
  • Thanks, I'm gonna check it out. – Aaron Sep 04 '15 at 07:01