Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 256
Oleksandr Avatar asked Sep 20 '25 01:09

Oleksandr


1 Answers

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.

like image 176
Brad Avatar answered Sep 21 '25 14:09

Brad