title: Testing in Spring project - injecting repository into service with Mockito
body: <p>I'm trying to understand how to use <strong>Mockito</strong> in a <strong>Spring</strong> project, but I'm a bit stuck with the following:</p>
  
  <p>I'm about to test a service with a real (in-memory) repository. I'm mocking every other object that's being used by that service. If I understand correctly, annotating an object with <code>@Mock</code> will be mocked, <code>@Spy</code> will use a real object, and with <code>@InjectMocks</code> will kind of "autowire" these annotated objects. However, I think I misunderstood <code>@Spy</code> because the following code is not working (seems like a mock object is inserted, neither a DB interaction, neither a <code>NullPointerException</code> comes up):</p>
  
  <pre><code>@SpringBootTest
  @RunWith(SpringRunner.class)
  public class UserServiceTests {
  
      @Spy
      @Autowired
      private UserRepository userRepository;
  
      @Mock
      private MessageService messageService;
  
      @InjectMocks
      private UserService userService = new UserServiceImpl();
  
      @Test
      public void testUserRegistration() {
          userService.registerUser("test@test.test");
  
          Assert.assertEquals("There is one user in the repository after the first registration.", 1, userRepository.count());
      }
  }
  </code></pre>
  
  <p>If I remove the <em>@Spy</em> annotation and insert the repository in the service with reflection, it works:</p>
  
  <pre><code>ReflectionTestUtils.setField(userService, "userRepository", userRepository);
  </code></pre>
  
  <p>This seems inconvenient, and I'm pretty sure that <code>@Spy</code> is meant to do this. Can anyone point out what I'm missing/misunderstanding?</p>
  
  <p><em>Edit:</em> one more thing - with the <code>@Spy</code> annotation I'm not getting a <code>NullPointerException</code> on save, but it seems like a mock object is inserted instead of the real repository.</p>
  
  <p><em>Edit 2:</em> I think this is the answer for my confusion:</p>
  
  <p><a href="https://stackoverflow.com/questions/43099556/springboot-junit-bean-autowire?rq=1">SpringBoot Junit bean autowire</a></p>