Mocking EntityManager (Mockito)
In your question, you use @Autowired
directly on the field for the system under test, which seems to instruct Spring to resolve the dependencies. It likely does so from your actual (production) configuration.
By comparison, a common Mockito annotation is @InjectMocks
, which ignores Spring, instantiates the object using as many @Mock
objects as possible.
Related SO question: Injecting into @Autowired variable during testing
Dax Durax
Updated on June 04, 2022Comments
-
Dax Durax almost 2 years
I have the following code in one of my classes:
@PersistenceContext protected EntityManager entityManager; public entryPoint() { for(Animal:getTheAnimals()) { System.out.println(Animal.getName()); } } private List<Animal> getTheAnimals() { return List<Animal>entityManager.createNamedQuery("myQuery").setParameter("myParam", new Date()).getResultList(); }
In my test class I have the following:
@Mock private EntityManager entityManager; @Mock private Query query; @Autowired private ClassToTest classToTest; @Test public void someTest() { List<Animal> list = new ArrayList<Animal>(); Mockito.when(entityManager.createNamdeQuery("myQuery")).thenReturn(query); Mockito.when(query.setParameter(any(String.class), any(java.util.Date.class)).getResultList()).thenReturn(list); ...something more here... }
As you can see the expected behavior is that the empty list is returned, and zero animal names get printed. However that is not the case and the actual animals from the db are being returned in the list. What am I missing? I tried several variations of this with the same result.
Thanks for reading.
-
xenoterracide about 7 yearsstale links, didn't copy relevant documentation into answer, didn't actually answer question.
-
Jeff Bowman about 7 yearsThanks for the review! I've updated the documentation link—it did go stale in the three years since the answer was posted. I do think it answers the question—why real dependencies might be used instead of mocks—but I understand if it doesn't give every reader the full context they may need. Cheers!
-
xenoterracide about 7 yearsbut it still doesn't answer the question, because I have the same problem, but am already using
@InjectMocks
-
Jeff Bowman about 7 yearsThat makes it different than the question above. You might want to ask a new question, potentially linking to this question and explaining the difference. I don't your problem is the same as the problem above, and I don't think the comment box will fit enough code and explanation to let me (or others) diagnose effectively.