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

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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.
Agreed... This old question dives into that in more detail: stackoverflow.com/questions/15228777/…
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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.