Testing spring-boot @service class

12,158

I assume that your AppProperties and MongoService is not in the same package

If not you can inject MongoService in that way :

create another class named TestConfiguration

@ComponentScan(basePackageClasses = {
        MongoService.class,
        AppProperties.class
})
@SpringBootApplication
public class TestConfiguration {
    public static void main(String[] args) {
        SpringApplication.run(TestConfiguration.class, args);
    }
}

And in the test just change to :

@RunWith(SpringRunner.class)
@SpringBootTest(classes = TestConfiguration.class) 
public class MongoServiceTest {

    private static final Logger logger = LoggerFactory.getLogger(MongoServiceTest.class);

    @Autowired
    MongoService mongoService;

    @Test
    public void MongoServiceAutowired() {   
        assertNotNull(mongoService);
    }
}
Share:
12,158
Andrea Girardi
Author by

Andrea Girardi

For the glory, for the money and for the fun. Mostly for the money! Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live. IT errors are like snowflakes They didn't drop the ball. They dropped the ball, kicked the coach in the nuts and took a crap in the quarterback's mouth If they see a scrambled mass of code that looks like it was written by a bevy of drunken sailors, then they are likely to conclude that the same inattention to detail pervades every other aspect of the project http://www.andreagirardi.it https://twitter.com/bazingaaaa

Updated on June 09, 2022

Comments

  • Andrea Girardi
    Andrea Girardi almost 2 years

    I want to test a @Service class that is normally called with SpringApplication.run().

    The service class is:

    @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&Browse database", e);
                throw new BackendException("Cannot create connection to Search&Browse database");
            }
        }
    
    }
    

    When it is called by the controller started with SpringApplication.run(), the MongoService is not null but, when I try from a jUnit it's not working.

    So, I'm trying this:

    @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);
        }
    }
    

    but I'm getting this exception:

    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)}

    Any clue? Where am I failing?