Aaron
Aaron

Reputation: 2755

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

Upvotes: 1

Views: 12768

Answers (2)

Henning
Henning

Reputation: 16311

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.

Upvotes: 3

Aaron
Aaron

Reputation: 2755

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

Upvotes: 1

Related Questions