4

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?

Hanna
  • 10,315
  • 11
  • 56
  • 89
Oleksandr
  • 2,346
  • 4
  • 22
  • 34
  • 2
    What are you trying to test? I seen no assert's. And where do you get your query from. if query is mocked you should not get a NPE. If you want to test the actual query you are creating an integration test where you usually have to setup your DAO's completely without mocking. – joostschouten Jun 22 '11 at 08:29

1 Answers1

12

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.

Brad
  • 15,186
  • 11
  • 60
  • 74