本机查询的Mockito NullPointerException(Mockito NullPointerException on Native Query)

编程入门 行业动态 更新时间:2024-10-24 10:17:46
本机查询的Mockito NullPointerException(Mockito NullPointerException on Native Query) java

我在查询对象上遇到问题,即使我用查询模拟对象将其存根,它也会变为空。这就是代码

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

我的测试方法是

Query query = mock(Query.class); when(entityManager.createNativeQuery("", SomeRandom.class)).thenReturn(query); List<SomeRandom> someList = requestDao.getSomeList(parameter, parameter, parameter, parameter);

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

最满意答案

这可能意味着您传递给mocked方法的其中一个匹配器不匹配。 您传递了一个实际的String实例(空字符串),它在引擎盖下转换为Equals匹配器 。 您的示例仅在queryString也是空字符串时才有效。

这应匹配任何查询字符串:

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

这是你期望传递的一些具体的字符串:

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

根据评论进行编辑:

如果从eq(SomeRandom.class)更改为any()解决了问题,则eq(SomeRandom.class)匹配器不匹配,这意味着SomeRandom.class不是实际传递给mocked方法的。

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.

更多推荐

本文发布于:2023-07-15 21:56:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1119327.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:本机   Mockito   NullPointerException   Native   Query

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!