anat0lius
anat0lius

Reputation: 2265

How do I properly configure my Spring Boot application?

Using mongodb with Spring Data MongoDB backend. Using Mongo Repositories too.

This is my actual configuration:

/** MONGO CLIENT *****************************************************/

@Override
protected String getDatabaseName() {
    return db;
}

@Override
public Mongo mongo() throws Exception {

    /* I'm so dump to automatize this that I just do it manually */

    return new Fongo("meh").getMongo();   //Using it for unit tests
    //return new MongoClient(url, port);  //Using it for IT
}

@Override
protected Collection<String> getMappingBasePackages() {
    return Arrays.asList("com.foo");
}


/** BEANS ************************************************************/

@Bean
public Jackson2RepositoryPopulatorFactoryBean repositoryPopulator() {

    Resource foo1 = (Resource) new ClassPathResource("collections/foo1.json");
    Resource foo2 = (Resource) new ClassPathResource("collections/foo2.json");


    Jackson2RepositoryPopulatorFactoryBean factory = new Jackson2RepositoryPopulatorFactoryBean();
    factory.setResources(new Resource[] { foo1, foo2 });
    return factory;
}

The repository populator is what I added and it's what gives me troubles. When I compile and test my project I'm getting DuplicateKeyException because I guess the repository populator triggers more than once.

These are the annotations that I use on my test classes:

@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc

Is it well configured my application? What's the reasonable solution to avoid repository populator to trigger multiple times ?

Upvotes: 1

Views: 854

Answers (1)

anat0lius
anat0lius

Reputation: 2265

Solution based on this guide (in spanish, sorry): https://www.paradigmadigital.com/dev/tests-integrados-spring-boot-fongo

  1. Is needed to separate fongo configuration from mongo.
  2. fongo configuration must be placed on test/

Just take the example code (and using MongoConfiguration.java too, my actual config is wrong) from the guide as a base and you will be fine.

Upvotes: 1

Related Questions