title: Testing spring-boot @service class
body: <p>I want to test a <code>@Service</code> class that is normally called with <code>SpringApplication.run()</code>.</p>
  
  <p>The service class is:</p>
  
  <pre><code>@Service
  @EnableConfigurationProperties(AppProperties.class)
  public class MongoService {
  
      private static final Logger logger = LoggerFactory.getLogger(MongoService.class);
  
      private MongoClient mongoClient;
  
      private final AppProperties properties;
  
      @Autowired
      public MongoService(AppProperties properties) {
          this.properties = properties;
      }
  
      /**
       * Open connection
       */
      public void openConnection() {
  
          try {
              mongoClient = new MongoClient(new MongoClientURI(properties.getMongoConnectionString()));
          } catch (Exception e) {
              logger.error("Cannot create connection to Search&amp;Browse database", e);
              throw new BackendException("Cannot create connection to Search&amp;Browse database");
          }
      }
  
  }
  </code></pre>
  
  <p>When it is called by the controller started with <code>SpringApplication.run()</code>, the <code>MongoService</code> is not null but, when I try from a jUnit it's not working.</p>
  
  <p>So, I'm trying this:</p>
  
  <pre><code>@RunWith(SpringRunner.class)
  @SpringBootTest
  @ContextConfiguration(classes = AppProperties.class)
  public class MongoServiceTest {
  
      private static final Logger logger = LoggerFactory.getLogger(MongoServiceTest.class);
  
      @Autowired
      MongoService mongoService;
  
      @Test
      public void MongoServiceAutowired() {   
          assertNotNull(mongoService);
      }
  }
  </code></pre>
  
  <p>but I'm getting this exception:</p>
  
  <blockquote>
    <p>org.springframework.beans.factory.UnsatisfiedDependencyException:
    Error creating bean with name 'mypackage.MongoServiceTest':
    Unsatisfied dependency expressed through field 'mongoService'; nested
    exception is
    org.springframework.beans.factory.NoSuchBeanDefinitionException: No
    qualifying bean of type 'mypackage.services.mongo.MongoService'
    available: expected at least 1 bean which qualifies as autowire
    candidate. Dependency annotations:
    {@org.springframework.beans.factory.annotation.Autowired(required=true)}</p>
  </blockquote>
  
  <p>Any clue? Where am I failing?</p>