Search code examples
javamongodbspring-bootjunitflapdoodle-embed-mongo

Junit tests failing with embedded mongodb with spring boot


I have added this code to configure embedded mongodb (de.flapdoodle.embed.mongo:2.2.0) with spring boot 2.7.10 :

@Configuration
public class TestMongoConfig {

    private MongodExecutable mongodExecutable;
    private MongoClient mongoClient;

    @Value("${mongo.db.host:localhost}")
    private String mongoHost;

    @Value("${mongo.db.port:27017}")
    private int mongoPort;

    @Value("${mongo.db.database:test}")
    private String mongoDatabase;

    @PostConstruct
    public void setup() throws Exception {
        MongodStarter starter = MongodStarter.getDefaultInstance();
        IMongodConfig mongodConfig = new MongodConfigBuilder()
                .version(Version.Main.V3_2)
                .net(new Net(mongoHost, mongoPort, Network.localhostIsIPv6()))
                .build();

        mongodExecutable = starter.prepare(mongodConfig);
        mongodExecutable.start();
        String connectionString = "mongodb://" + mongoHost + ":" + mongoPort;
        mongoClient = MongoClients.create(connectionString);
    }

    @PreDestroy
    public void cleanup() {
        mongodExecutable.stop();
        mongoClient.close();
    }

    @Bean
    public MongoTemplate mongoTemplate() {
        return new MongoTemplate(mongoClient, mongoDatabase);
    }
}

I am adding this to my test class like this :

@Autowired
private MongoTemplate mongoTemplate;

Few tests are getting failed with this error :

Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'testMongoConfig': Invocation of init method failed; nested exception is java.io.IOException: Could not start process: failed errno:10048 Only one usage of each socket address (protocol/network address/port) is normally permitted. for socket: 127.0.0.1:27017

2023-04-04T10:11:42.087+0530 E STORAGE  [initandlisten] Failed to set up sockets during startup.

Solution

  • I resolved it by adding this code in the setup() method. This will automatically allocate the available port.

            MongodStarter starter = MongodStarter.getDefaultInstance();
            ServerSocket socket = new ServerSocket(0); // create a socket with a random port
            mongoPort = socket.getLocalPort(); // get the port number
            socket.close(); // close the socket