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