Parameter named query testing with mockito

Oleksandr picture Oleksandr · Jun 22, 2011 · Viewed 16k times · Source

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?

Answer

Brad picture Brad · Jun 23, 2011

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.