title: How to mock Spring Data and unit test service
body: <p>I'm trying to unit test a service method. The service methods calls a spring data repository method to fetch some data. I want to mock that repository call, and supply the data myself. How to do that? Following <a href="http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#boot-features-testing-spring-boot-applications-mocking-beans" rel="noreferrer">Spring Boot documentation</a>, when I mock the repository and call the repository method directly in my test code, the mock is working. But when I call the service method, which in turn would call the repository method,  mocking isn't working. Below is the sample code:</p>
  
  <p>Service class:</p>
  
  <pre><code>@Service
  public class PersonService {
  
      private final PersonRepository personRepository;
  
      @Autowired
      public PersonService(personRepository personRepository) {
  
          this.personRepository = personRepository;
      }
  
      public List&lt;Person&gt; findByName(String name) {
          return personRepository.findByName(name); // I'd like to mock this call
      }
  }
  </code></pre>
  
  <p>Test class:</p>
  
  <pre><code>@RunWith(SpringRunner.class)
  @SpringBootTest
  public class ApplicationTests {
  
      // http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#boot-features-testing-spring-boot-applications-mocking-beans
      @MockBean
      private PersonRepository personRepository;
  
      @Autowired
      private PersonService personService;
  
      private List&lt;Person&gt; people = new ArrayList&lt;&gt;();
  
      @Test
      public void contextLoads() throws Exception {
  
          people.add(new Person());
          people.add(new Person());
  
          given(this.personRepository.findByName("Sanjay Patel")).willReturn(people);
  
          assertTrue(personService.findByName("Sanjay Patel") == 2); // fails
      }
  }
  </code></pre>