2

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.

Dax Durax
  • 1,607
  • 5
  • 23
  • 31

1 Answers1

2

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

Community
  • 1
  • 1
Jeff Bowman
  • 90,959
  • 16
  • 217
  • 251
  • stale links, didn't copy relevant documentation into answer, didn't actually answer question. – xenoterracide Mar 20 '17 at 17:24
  • Thanks 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! – Jeff Bowman Mar 20 '17 at 17:35
  • but it still doesn't answer the question, because I have the same problem, but am already using `@InjectMocks` – xenoterracide Mar 20 '17 at 17:48
  • That 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. – Jeff Bowman Mar 20 '17 at 18:50