【问题标题】:Testing spring-boot @service class测试 spring-boot @service 类
【发布时间】:2018-06-10 02:32:42
【问题描述】:

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

服务类是:

@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: 创建名为“mypackage.MongoServiceTest”的 bean 时出错: 通过字段 'mongoService' 表达的不满足的依赖关系;嵌套的 例外是 org.springframework.beans.factory.NoSuchBeanDefinitionException: 否 'mypackage.services.mongo.MongoService' 类型的合格 bean 可用:预计至少有 1 个符合 autowire 条件的 bean 候选人。依赖注解: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

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

【问题讨论】:

  • @SpringBootTest 正在寻找 @SpringBootApplication,它需要位于项目的根级别(因为它递归搜索 Spring 组件/配置)[或以其他方式指定在哪里寻找东西通过@ComponentScan]。是这样吗?
  • 我添加了@ComponentScan 但没有成功(jUnits 存储在 /test 文件夹中)

标签: java spring spring-mvc spring-boot spring-test


【解决方案1】:

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

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

创建另一个名为TestConfiguration的类

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-06-01
    • 2022-11-11
    • 2018-02-25
    • 2019-01-29
    • 2019-01-21
    • 1970-01-01
    • 2019-03-13
    • 2016-10-29
    相关资源
    最近更新 更多