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