开发者

Parameter named query testing with mockito

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.开发者_JAVA技巧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?


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

@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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜