简体   繁体   中英

Mockito NullPointerException on Native Query

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM