java 使用 mockito 进行参数命名查询测试

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6435620/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 15:52:44  来源:igfitidea点击:

Parameter named query testing with mockito

javajpajunitmockitonamed-query

提问by Oleksandr

I want to write a Junit test for my dao, but I have a problem. Here is the method I want to test:

我想为我的 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;
        }

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?

查询和 entityManager 被模拟。我有NPE,这并不奇怪,我无法调用该方法,因为查询是和接口。那么有人可以告诉我在测试时在 NamedQueries 中设置参数的最佳方法吗?

回答by Brad

You're supposed to be creating a mock of the Query interface like this...

你应该像这样创建一个 Query 接口的模拟......

@Test
public void test() { 

    Query query = mock(Query.class);

    when(entityManager.createNamedQuery(queryName)).thenReturn(query);

    ...

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.

也许您忘记了字符串文字“queryName”周围的双引号。从您的代码中,我看不到上面最后一行中变量 queryName 的定义位置。