测试 spring-boot @service class

Testing spring-boot @service class

我想测试通常用 SpringApplication.run() 调用的 @Service class。

服务 class 是:

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

}

当它被以 SpringApplication.run() 开头的控制器调用时,MongoService 不为空,但是当我从 jUnit 尝试时它不起作用。

所以,我正在尝试这个:

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

但我遇到了这个异常:

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

有线索吗?我哪里失败了?

我假设你的 AppPropertiesMongoService 不在同一个包中

如果没有,您可以通过这种方式注入 MongoService

创建另一个名为 TestConfiguration

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

并且在测试中只需更改为:

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