Search code examples
junitjunit4entitymanager

Test case for entity manager


Getting a null pointer exception on Mockito.when for the below code line.

when(entityManager.createQuery(any(String.class)).setParameter(any(String.class), any(String.class)).getSingleResult()).thenReturn("2");

Trying to mock entity manager which is declared as

@Mock
private EntityManager entityManager;

Any help to resolve this?

Complete test class

@RunWith(MockitoJUnitRunner.class)
public class ASDAOImplTest {

    @InjectMocks
    ASDAOImpl asdaoImpl=new ASDAOImpl();
    @Mock
    private EntityManager entityManager;

    @Before
    public void setUp()
    {
        ReflectionTestUtils.setField(asdaoImpl,"capLimit", 1);
    }

    @Test
    @Ignore
    public void validateCappingTest()
    {
        when(entityManager.createQuery(any(String.class)).setParameter(any(String.class), any(String.class)).getSingleResult()).thenReturn("2");
        asdaoImpl.validateCapping("2");
    }
}

Solution

  • Edit: Ah, spoke to soon. The error is here...

    when(entityManager.createQuery(any(String.class)).setParameter(...)
    

    entityManager is a mock. Per default, a mock will return null. So, entityManager.createQuery(...) will return null. Calling setParameter on null is a NPE.

    What you need to insert is a query mock...

    @Mock
    private Query query;
    
    ...
    
    // when createQuery is called, return the mocked query object (instead of null)
    when(entityManager.createQuery(any(String.class)).thenReturn(query);
    
    // make sure that setParameter returns this query object back (would otherwise also be NPE)
    when(query.setParameter(any(String.class), any(String.class)).thenReturn(query);
    
    // And return the desired result from getSingleResult
    when(query.getSingleResult()).thenReturn("2");
    

    Old answer:

    Hard to say without the complete code, but a guess would be that you are misssing the Mockito initialization (the part that actually creates object for the variables annotated with @Mock). This can be done in at least two ways:

    // Run the whole test with the Mockito runner...
    @RunWith(MockitoJUnitRunner.class) 
    public class MyTestClass { ...
    

    or...

    // Do the Mockito initialization "manually"
    @Before
    public void init() {
        MockitoAnnotations.initMocks(this);
    }
    

    Both ways will lead to Mockito creating all the objects where the variables are annotated with @Mock (it also handles @InjectMocks, etc.).

    If this doesn't help, you will have to post more of your test class, otherwise probably noone can help.