【发布时间】: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