首页 > 解决方案 > Spring测试:ApplicationContext配置类(spring data mongodb)

问题描述

我只想测试 mongo 相关的代码。这是我的测试代码片段:

@RunWith(SpringRunner.class)
@ContextConfiguration(classes = {MongoConfig.class})
@SpringBootTest
public class ModelTest {

    @Autowired
    private MongoTemplate mongoTemplate;

如您所见,我使用@ContextConfiguration它是为了仅加载与 Mongo 相关的配置:

@Configuration
public class MongoConfig {

    @Bean
    public CustomConversions customConversions(){
        List<Converter<?, ?>> converters = new ArrayList<Converter<?, ?>>();
        converters.add(new ReferenceWriterConverter());
        return new MongoCustomConversions(converters);
    }

}

正如您所看到的,它仅旨在加载将要使用的自定义转换器mongoTemplate,以便将对象序列化到 mongodb 数据库。

还有,src/test/resources/application.properties是:

spring.data.mongodb.host: localhost
spring.data.mongodb.port: 27017

问题是,当我尝试运行测试时,它给了我一个Unsatisfied dependency expressed through field 'mongoTemplate'

UnsatisfiedDependencyException:创建名为“net.gencat.transversal.repositori.digital.mongo.ModelTest”的bean时出错:通过字段“mongoTemplate”表达的不满足依赖关系;嵌套异常是 org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.springframework.data.mongodb.core.MongoTemplate' available

相关项目依赖:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
</dependency>

有任何想法吗?

标签: springspring-dataspring-data-mongodb

解决方案


您尝试在此处加载自定义 mongo 配置 @Bean 客户端或扩展似乎有问题AbstractMongoConfiguration

在此处更改您的数据库名称,而不是demo

@Configuration
public class MongoConfig extends AbstractMongoConfiguration {

   @Override
   protected String getDatabaseName() {
      return "demo";
   }

  @Override
   public MongoClient mongoClient() {
    return new MongoClient("localhost", 27017);
  }

   @Bean
   public CustomConversions customConversions(){
       List<Converter<?, ?>> converters = new ArrayList<Converter<?, ?>>();
       converters.add(new ReferenceWriterConverter());
       return new MongoCustomConversions(converters);
   }

}


推荐阅读