本机查询上的 Mockito NullPointerException

Mockito NullPointerException on Native Query(本机查询上的 Mockito NullPointerException)
本文介绍了本机查询上的 Mockito NullPointerException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我的查询对象有问题,即使我使用查询模拟对象存根它,它也会变为空.这是代码

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.

我的测试方法是

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

推荐答案

这可能意味着您传递给模拟方法的匹配器之一不匹配.您传递了一个实际的 String 实例(空字符串),该实例在后台转换为 Equals 匹配器.只有当 queryString 也是空字符串时,您的示例才有效.

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

根据评论

如果从 eq(SomeRandom.class) 更改为 any() 解决了问题,那么 eq(SomeRandom.class) 匹配器不匹配,这意味着 SomeRandom.class 实际上不是传递给模拟方法的内容.

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.

这篇关于本机查询上的 Mockito NullPointerException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

Sending a keyboard event from java to any application (on-screen-keyboard)(将键盘事件从 java 发送到任何应用程序(屏幕键盘))
How to make JComboBox selected item not changed when scrolling through its popuplist using keyboard(使用键盘滚动其弹出列表时如何使 JComboBox 所选项目不更改)
Capturing keystrokes without focus(在没有焦点的情况下捕获击键)
How can I position a layout right above the android on-screen keyboard?(如何将布局放置在 android 屏幕键盘的正上方?)
How to check for key being held down on startup in Java(如何检查在Java中启动时按住的键)
Android - Get keyboard key press(Android - 获取键盘按键)