1

I have a piece of code that reads something like this:

entityManager.find(SomeClass.class, Long id, OtherClass.class, Session session);

Can I use Mockito to mock it out and return a desired value?

Thanks

Deb
  • 1,918
  • 1
  • 18
  • 18

2 Answers2

3

Yes, something like this will do it:

import static org.mockito.Mockito.*;
import static org.junit.Assert.*;
import org.junit.Test;

....

   @Test
   public void yourMockTest(){

    // create your Mock
    EntityManager entityManager = mock(EntityManager.class);

    // instantiate your args
    Class clazz = SomeClass.class;
    Long id = 1000L;
    Class otherClazz = OtherClass.class
    Session session = new SessionImpl();

    // instantate return object
    SomeClass returnMe = new SomeClass();

    // mock
    when(entityManager.find(any(), any(), any(), any()).thenReturn(returnMe);

    // execute
    Object returned = entityManager.find(clazz, id, otherClazz, session);

    // assert
    assertEquals(returnMe, returned);
   }

Edit: chill makes the good point you'll likely be dealing with an EntityManager in some other class. This old question demonstrates how to use Mockito to inject mocks into other objects.

Community
  • 1
  • 1
Dean Clark
  • 3,770
  • 1
  • 11
  • 26
  • 1
    In a real situation, OP would probably be calling a service method. `@Mock` would be used to annotate an `EntityManager` field in the test and `@InjectMocks` would be used to annotate a `ServiceClass` field in the test. That way, the test would call something like `myServiceClass.doServiceAction()`, which will call the mocked `EntityManager` as part of its code. – Chill May 03 '16 at 16:40
  • Agreed... This old question dives into that in more detail: http://stackoverflow.com/questions/15228777/how-does-mockito-injectmocks-work – Dean Clark May 03 '16 at 16:43
2

Short answer is yes. EntityManager is an interface, perfectly "mock-able" with Mockito. It'd be something like this:

EntityManager mocked = mock(EntityManager.class);
when(mocked.find(any(), any(), any(), any()).thenReturn(yourMockedValue)
Ulises
  • 9,115
  • 2
  • 30
  • 27