使用mockito进行参数命名查询测试
我想为我的 dao 编写一个 Junit 测试,但我有一个问题。这是我想测试的方法:
public boolean boo(final String param) {
final Query query = this.entityManager.createNamedQuery("queryName");
query.setParameter(1, param);
boolean isExists = false;
if(query.getResultList().size() != 0) {
isExists = true;
}
return isExists;
}
该方法的问题是:
query.setParameter(1, param);
当我编写如下内容时:
@Test
public void test() {
when(entityManager.createNamedQuery(queryName)).thenReturn(query);
when(query.getResultList()).thenReturn(new ArrayList());
//when(query.setParameter(1,project.getName())).thenCallRealMethod();
projectDao.boo(name);
}
查询和实体管理器被模拟。 我有 NPE,这并不奇怪,我无法调用该方法,因为查询是和接口。 那么有人可以告诉我在测试时在 NamedQueries 中设置参数的最佳方法吗?
I want to write a Junit test for my dao, but I have a problem. Here is the method I want to test:
public boolean boo(final String param) {
final Query query = this.entityManager.createNamedQuery("queryName");
query.setParameter(1, param);
boolean isExists = false;
if(query.getResultList().size() != 0) {
isExists = true;
}
return isExists;
}
The problem with this method is :
query.setParameter(1, param);
When I write something like :
@Test
public void test() {
when(entityManager.createNamedQuery(queryName)).thenReturn(query);
when(query.getResultList()).thenReturn(new ArrayList());
//when(query.setParameter(1,project.getName())).thenCallRealMethod();
projectDao.boo(name);
}
The query and entityManager are mocked.
I have NPE, and this is not a surprise, and I cannot call the method because the query is and interface.
So could somebody tell me the best way to set parameters in NamedQueries while testing?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您应该像这样创建查询接口的模拟...
也许您忘记了字符串文字“queryName”周围的双引号。从您的代码中我看不到上面最后一行定义变量 queryName 的位置。
You're supposed to be creating a mock of the Query interface like this...
Maybe you forgot the double quotes around the String literal "queryName". From your code I cannot see where the variable queryName is defined on the last line above.