如何在 SpringBoot 2.7.13 中使用嵌入式 MongoDB

问题描述 投票:0回答:1

我正在尝试使用嵌入式 mongodb 进行集成测试,并且我正在使用 de.flapdoodle.embed.mongo 来实现此目的。但是无论我尝试使用什么 mongodb 版本,我都会收到连接拒绝异常。请找到我的配置。

pom.xml 具有以下依赖项

   <dependency>
      <groupId>de.flapdoodle.embed</groupId>
      <artifactId>de.flapdoodle.embed.mongo</artifactId>
      <version>3.5.3</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.mongodb</groupId>
      <artifactId>mongo-java-driver</artifactId>
      <version>3.8.2</version>
      <scope>test</scope>
    </dependency>

来自 TEST 的 application.yml 定义了以下 mongo db 版本。

spring:  
  mongodb:
    embedded:
      version: 4.0.2

我尝试将以下内容添加到 application.yml 中进行测试

de:
  flapdoodle:
    mongodb:
      embedded:
        version: 4.0.2

以下是我用于此项目的 springboot 父级

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.7.13</version>
  </parent>

非常感谢任何帮助。

mongodb spring-boot spring-data-mongodb flapdoodle-embed-mongo
1个回答
0
投票

2014年7月2日春季

(de.flapdoodle.embed.mongo.version=3.5.4)

/**
 * Embedded MongoDB singleton.
 * Add @Import(EmbeddedMongoDb.class) to Test* classes
 */
public class EmbeddedMongoDb implements Closeable {

    private static final String CONNECTION_STRING = "mongodb://%s:%d";
    private static MongoClient create;
    private static MongodExecutable mongodExecutable;

    private static MongoTemplate mongoTemplate;

    @Bean
    public MongoTemplate mongoTemplate() throws Exception {

        if (mongoTemplate == null) {
            String ip = "localhost";
            int port  = 17027;

            MongodConfig mongodConfig = ImmutableMongodConfig.builder()
                    .net(new Net(ip, port, Network.localhostIsIPv6()))
                    .version(Version.Main.V6_0).build();

            MongodStarter starter = MongodStarter.getDefaultInstance();
            mongodExecutable = starter.prepare(mongodConfig);
            mongodExecutable.start();
            create = MongoClients.create(String.format(CONNECTION_STRING, ip, port));
            mongoTemplate = new MongoTemplate(create, "test");
        }

        return mongoTemplate;    
    }

    @Override
    public void close() throws IOException {
        create.close();
        mongodExecutable.stop();
        mongoTemplate = null;
    }
}

春季+3.1.2

(de.flapdoodle.embed.mongo.version=4.7.1)

/**
 * Embedded MongoDB singleton.
 * Add @Import(EmbeddedMongoDb.class) to Test* classes
 */
public class EmbeddedMongoDb implements Closeable {

    private static final String CONNECTION_STRING = "mongodb://%s:%d";
    private static ReachedState<RunningMongodProcess> mongod;
    private static MongoClient client;
    private static MongoTemplate mongoTemplate;

    @Bean
    public MongoTemplate mongoTemplate() throws Exception {

        if (mongoTemplate == null) {

            int port = 17027;

            //Store database in temp folder
            //More info: https://stackoverflow.com/a/1924576/3710490
            String tmpdir    = System.getProperty("java.io.tmpdir");
            File databaseDir = new File(tmpdir, "database");
            if(!databaseDir.exists()) {
                Files.createDirectory(databaseDir.toPath());    
            }
            
            ImmutableMongod mongodWithoutAuth = Mongod.builder()
                    .net(Start.to(Net.class).initializedWith(Net.defaults().withPort(port)))
                    .databaseDir(Start.to(DatabaseDir.class).initializedWith(DatabaseDir.of(databaseDir.toPath()))).build();

            mongod                = mongodWithoutAuth.start(Version.Main.V6_0);
            ServerAddress address = mongod.current().getServerAddress();
            client = MongoClients.create(String.format(CONNECTION_STRING, address.getHost(), address.getPort()));
            
            mongoTemplate = new MongoTemplate(client, "test");
        }

        return mongoTemplate;
    }

    @Override
    public void close() throws IOException {
        
        if (mongod.current().isAlive()) {
            client.close();
            mongod.current().stop();
            mongoTemplate = null;
        }
    }
}

测试

@SpringBootTest(classes = {
    Target.class // Instantiate only the necessary classes
})
@Import(EmbeddedMongoDb.class)
class TargetClassTest {
    
    @Autowired
    private MongoTemplate mongoTemplate;
    
    @BeforeEach
    void init() throws IOException {
        //Drop all collections
        mongoTemplate.getCollectionNames().forEach(mongoTemplate::dropCollection);
    }
    
    @Test
    void testSomeMethod() throws IOException {
        
        //WHEN
        String collection = "some_collection";
        Document doc  = new Document("field", "value1");
        Document doc2 = new Document("field", "value2");
        Document doc3 = new Document("field", "value3");
        
        //THEN
        mongoTemplate.insert(Arrays.asList(doc, doc2, doc3), collection);
                
        //VERIFY
        Assertions.assertTrue(mongoTemplate.collectionExists(collection),        "Wrong result");
        Assertions.assertEquals(3, mongoTemplate.count(new Query(), collection), "Wrong result");
        Assertions.assertEquals(2, mongoTemplate.count(Query.query(Criteria.where("field").in(doc2.getString("field"), doc3.getString("field"))), collection), "Wrong result");
        Assertions.assertEquals(1, mongoTemplate.count(Query.query(Criteria.where("field").gt(doc2.getString("field"))), collection),                          "Wrong result");
        Assertions.assertEquals(0, mongoTemplate.count(Query.query(Criteria.where("field2").exists(Boolean.TRUE)), collection),                                "Wrong result");     
    }
}

注意:无需

mongo-java-driver
依赖。

© www.soinside.com 2019 - 2024. All rights reserved.