我可以使用fongo的存储库populator bean吗?

时间:2017-06-02 07:06:56

标签: mongodb unit-testing spring-data fongo

我正在使用Fongo不仅用于单元测试,还用于集成测试,所以我想用一些集合初始化Fongo,这可能吗?

这是我的java配置(based on Oliver G. answer):

@EnableAutoConfiguration(exclude = { 
    EmbeddedMongoAutoConfiguration.class,
    MongoAutoConfiguration.class,
    MongoDataAutoConfiguration.class
})
@Configuration
@ComponentScan(basePackages = { "com.foo" },
    excludeFilters = { @ComponentScan.Filter(classes = { SpringBootApplication.class }) 
})
public class ConfigServerWithFongoConfiguration extends AbstractFongoBaseConfiguration {

    private static final Logger log = LoggerFactory.getLogger(ConfigServerWithFongoConfiguration.class);

    @Autowired
    ResourcePatternResolver resourceResolver;

    @Bean
    public Jackson2RepositoryPopulatorFactoryBean repositoryPopulator() {

        Jackson2RepositoryPopulatorFactoryBean factory = new Jackson2RepositoryPopulatorFactoryBean();
        try {
            factory.setResources(resourceResolver.getResources("classpath:static/collections/*.json"));
        } catch (IOException e) {
            log.error("Could not load data", e);
        }
        return factory;
    }

}

当我运行我的IT测试时,在日志上显示Reading resource: file *.json但测试失败,因为它们从Fongo数据库中没有检索到任何内容(null)。

测试用以下内容注释:

@RunWith(SpringRunner.class)
@SpringBootTest(classes={ConfigServerWithFongoConfiguration.class})
@AutoConfigureMockMvc
@TestPropertySource(properties = {"spring.data.mongodb.database=fake"})
@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS)

1 个答案:

答案 0 :(得分:0)

哈哈,我现在感觉很蠢。是格式问题。 JSON集合必须像这样格式化:

[
  {/*doc1*/},
  {/*doc2*/},
  {/*doc3*/}
]

我错过了[]和逗号分隔的文档。