title: DataJpaTest with a single autowired tested bean
body: <p>I would like to create a test, which targets exactly one service class (<code>@Service</code>) in my project. </p>
  
  <p>My service class has two kinds of dependencies:</p>
  
  <ul>
  <li>other services, which I want to mock with a <code>@MockBean</code></li>
  <li>JPA repositories, which I do not want to mock; I want them to be real Spring beans, configured against H2 database</li>
  </ul>
  
  <p>My services only depend on other services or repositories. Repositories have no dependencies - imagine JPA repository interfaces.</p>
  
  <p>I have come up with following solution, which works fine:</p>
  
  <pre><code>@DataJpaTest
  class FooServiceTests {
  
      @Autowired
      private FooRepository fooRepository;
  
      @MockBean
      private BarService barService;
  
      @Test
      void testService() {
          FooService fooService = new FooService(barService, fooRepository);
          Assertions.assertNotNull(barService);
          Assertions.assertNotNull(fooRepository);
      }
  
  }
  </code></pre>
  
  <p>My question is, whether there is an alternative to this solution, which does not require manual assembly of the tested bean. A solution, which would have Spring assemble the bean for me, by using mocked services and real (H2) repositories. A solution, which allows tested bean to have dependencies <code>@Autowired</code> into private fields. Something like this: (which obviously does not work):</p>
  
  <pre><code>@DataJpaTest
  @ContextConfiguration(classes = FooService.class)
  class FooService2Tests {
  
      @MockBean
      private BarService barService;
  
      @Autowired
      private FooService fooService;
  
      @Test
      void testService() {
          Assertions.assertNotNull(fooService);
          Assertions.assertNotNull(barService);
          Assertions.assertNotNull(fooService.getBarService());
          Assertions.assertNotNull(fooService.getFooRepository());
      }
  
  }
  </code></pre>
  
  <p>I wanted to avoid using <code>@SpringBootTest</code>. If some answer suggests so, than it should explain, why that is the best way on how to go.</p>