javaspringmongodbspring-mongofongo

Override Spring Mongo config with Fongo


I have a Spring application using the Spring-Mongo integration. In the main app config XML we have stuff like this to define the Mongo instances (there are several):

<mongo:mongo id="mongoOne" replica-set="#{hostUrl}" >
    <mongo:options connections-per-host="25"
                   threads-allowed-to-block-for-connection-multiplier="5"
                   connect-timeout="10000"
                   max-wait-time="120000"
                   auto-connect-retry="true"
                   socket-keep-alive="true"
                   socket-timeout="5000" />
</mongo:mongo>

I would like to override this in our BDD suite configuration with Fongo so the tests don't use real mongo.

I'm a little thrown off by what exactly "mongo:mongo" is setting up. I was expecting that eventually you get a com.mongodb.Mongo out of it. the XML seems to refer to a Spring MongoType?

I had attempted this in my BDD config but it doesn't work:

@Bean(name = "mongoOne") @Primary
public Mongo mongoOne() { 
    return new Fongo("mongoOne").getMongo(); 
}

Solution

  • In your test application context you need configure fongo like this:

    <bean name="fongo" class="com.github.fakemongo.Fongo">
        <constructor-arg value="InMemoryMongo" />
    </bean>
    <bean id="mongo" factory-bean="fongo" factory-method="getMongo" />
    
    <mongo:db-factory id="mongoDbFactory" mongo-ref="mongo" />
    
    <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
        <constructor-arg ref="mongoDbFactory"/>
    </bean>
    

    It will override mongoTemplate to use in memory mongo implementation. Make sure your test application context is picked up by your tests.