title: Unit test in Spring: injecting a dependency into a component under test
body: <p>I have a very simple rest controller:</p>
  
  <pre><code>@RestController
  public class MyController {
      @Autowired
      public Logger logger;
  </code></pre>
  
  <p>The logger dependency gets injected via the following configuration:</p>
  
  <pre><code>@Configuration
  public class MyConfig {
      @Bean
      public Logger logger() {
          return LoggerFactory.getLogger(MyController.class);
      }
  </code></pre>
  
  <p>If I run the Spring application that contains the controller then everything works fine. However, I cannot manage to achieve this dependency injection when running my unit tests. In this case I have the following test configuration:</p>
  
  <pre><code>@Configuration
  @Profile("test")
  public class MyTestConfig {
      @Bean
      public Logger logger() {
          return LoggerFactory.getLogger(MyCOntroller.class);
      }
  </code></pre>
  
  <p>And this is the relevant part of my unit tests code:</p>
  
  <pre><code>@RunWith(MockitoJUnitRunner.class)
  @ContextConfiguration(classes = MyTestConfig.class)
  @ActiveProfiles("test")
  public class MyContollerTest {
  </code></pre>
  
  <p>However the logger object does not get "autowired" in <code>MyController</code> (note that I do not want to mock the logger object), which results in a null pointer reference.</p>
  
  <p>What am I missing?</p>