mongodbunit-testingspring-datafongo

Can I use repository populator bean with fongo?


I'm using Fongo not only for unit tests but also for integration tests so I would like to initialize Fongo with some collections, is that possible?

This is my java config (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;
    }

}

When I run my IT tests, on the log it appears Reading resource: file *.json but the tests fails because they retrieve nothing (null) from Fongo database.

Tests are annotated with:

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

Solution

  • Lol, I feel so stupid right now. Was format issue. JSON collections must be formated like this:

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

    I was missing the [] and comma separated documents.