Как сделать интеграционное тестирование для собственного хранилища Монго? - PullRequest
1 голос
/ 06 мая 2019

Это следующая конфигурация, которую я выполнил в своем проекте.

    @Configuration

    public class AppMongoConfig {

      @Autowired private MongoDbFactory mongoDbFactory;

      @Autowired private MongoMappingContext mongoMappingContext;

      @Bean
      public MappingMongoConverter mappingMongoConverter() {

        DbRefResolver dbRefResolver = new DefaultDbRefResolver(mongoDbFactory);
        MappingMongoConverter converter = new MappingMongoConverter(dbRefResolver, mongoMappingContext);
        converter.setTypeMapper(new DefaultMongoTypeMapper(null));

        return converter;
      }
    }
@Configuration
@RequiredArgsConstructor
@EnableConfigurationProperties(MultipleMongoProperties.class)
public class MultipleMongoConfig {

  private final MultipleMongoProperties mongoProperties;

  @Primary
  @Bean(name = "primaryMongoTemplate")
  public MongoTemplate primaryMongoTemplate() throws Exception {
    return new MongoTemplate(primaryFactory(this.mongoProperties.getPrimary()));
  }

  @Bean(name = "secondaryMongoTemplate")
  public MongoTemplate secondaryMongoTemplate() throws Exception {
    return new MongoTemplate(secondaryFactory(this.mongoProperties.getSecondary()));
  }

  @Bean
  @Primary
  public MongoDbFactory primaryFactory(final MongoProperties mongo) throws Exception {
    return new SimpleMongoDbFactory(new MongoClientURI(mongo.getUri()));
  }

  @Bean
  public MongoDbFactory secondaryFactory(final MongoProperties mongo) throws Exception {
    return new SimpleMongoDbFactory(new MongoClientURI(mongo.getUri()));
  }
}


@Data
@ConfigurationProperties(prefix = "mongodb")
public class MultipleMongoProperties {
    private MongoProperties primary = new MongoProperties();
    private MongoProperties secondary = new MongoProperties();
}


@Configuration
@EnableMongoRepositories(
    basePackages = {"com.student.repository.primary"},
    mongoTemplateRef = "primaryMongoTemplate")
public class PrimaryMongoConfig {}

@Configuration
@EnableMongoRepositories(
    basePackages = {"com.student.repository.secondary"},
    mongoTemplateRef = "secondaryMongoTemplate")
public class SecondaryMongoConfig {}

Код репозитория:

 public interface StudentDAO {

      Student save(StudentInfo studentInfo); 
} 

@Repository 
public class StudentDAOImpl implements StudentDAO {

      @Autowired   @Qualifier("primaryMongoTemplate")   
      private MongoTemplate mongoTemplate;

      @Override   public StudentInfo save(StudentInfo userWatchlist) {
        return mongoTemplate.save(userWatchlist);   
     } 
}

Код тестирования интеграции:

@RunWith(SpringRunner.class)
@DataMongoTest(includeFilters = @Filter(Repository.class))
public class WatchListDAOImplIT {

  @Autowired private StudentDAO studentDAO;

  @Test
  public void save() {
    StudentInfo studentInfo = getStudentInfo();
    StudentInfo dbUserWatchlist = watchListDAO.save(studentInfo);
    Assert.assertEquals(studentInfo.getId(), dbUserWatchlist.getId());
  }

  private StudentInfo getStudentInfo() {
    StudentInfo studentInfo = new StudentInfo();
    studentInfo.setId(9999999l);
    return studentInfo;
  }
}

Который дает мне следующую ошибку: -

java.lang.IllegalStateException: не удалось загрузить ApplicationContext

в org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadConteD (defaultCacheAaderDelegate.loadConteD (defaultCacheAaderDatelegateAAccessContextAteCateAccessTacheteo.Alache.Java: 125) в org.springframework.test.context.support.DefaultTestContext.getApplicationContext (DefaultTestContext.java:108) в org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDava.factory.UnsatisfiedDependencyException: Ошибка создания бина с именем 'appMongoConfig': Неудовлетворенная зависимость, выраженная через поле 'mongoDbFactory'; вложенным исключением является org.springframework.beans.factory.UnsatisfiedDependencyException: Ошибка созданияbean-компонент с именем «primaryFactory», определенным в ресурсе пути к классу [... / config / mongo / MultipleMongoConfig.class]: неудовлетворенная зависимость, выраженная через метод «primaryFactory», параметр 0;вложенное исключение - org.springframework.beans.factory.NoSuchBeanDefinitionException: нет доступного квалифицирующего компонента типа 'org.springframework.boot.autoconfigure.mongo.MongoProperties': ожидается, что по крайней мере 1 компонент будет квалифицирован как кандидат для автоматической передачи.Аннотации зависимостей: {}

Вызвано: org.springframework.beans.factory.NoSuchBeanDefinitionException: нет квалифицированного компонента типа 'org.springframework.boot.autoconfigure.mongo.MongoProperties': ожидается, что по крайней мере 1

Пожалуйста, помогите относительно этого.

...