测试中嵌入了mongodb thow MongoSocketReadException

时间:2018-10-10 09:19:43

标签: mongodb spring-boot testing junit5

我配置了嵌入式mongodb进行测试。如果它们全部执行,则MongoSocketReadException: Exception receiving message Caused by: java.net.SocketException: Connection reset会出现在不同的测试中。但是,当他们每个人一个一个地执行时,没有任何问题。

通过以下方式进行配置

   @DependsOn("embeddedMongoServer") // name has been taken from org.springframework.boot.autoconfigure.mongo.embedded.EmbeddedMongoAutoConfiguration.embeddedMongoServer
@Bean                                    // client should start after server start
public MongoClient getMongoClient(IMongodConfig: mongodConfig){
    return new MongoClient(mongodConfig.net().getSserverAddress.getHostName, mongodConfig.net().getPort)
}

并且主类具有以下注释:@SpringBootApplication(exclude = [MongoAutoConfiguration::class, MongoDataAutoConfiguration::class, EmbeddedMongoAutoConfiguration::class])

在pom中,我有以下内容(未使用spring数据):

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.0.3.RELEASE</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>
<dependency>
        <groupId>de.flapdoodle.embed</groupId>
        <artifactId>de.flapdoodle.embed.mongo</artifactId>
</dependency>
<dependency>
        <groupId>org.mongodb</groupId>
        <artifactId>mongo-java-driver</artifactId>
        <version>3.6.4</version>
    </dependency>

测试通过以下方式使用mongodb:

@ExtendWith(SpringExtension::class)
@SpringBootTest

class SomeTest{

@Resource
private MongoClient mongoClient;
private MongoDatabase db;

@BeforeEach
public void prepareDb() {
    db = mongoClient.getDatabase("dbName")
    mongoCollection = db.getCollection("collection")
}

class BasicTestsWithSampleData {
 @BeforeEach
    public populateDb(){
        mongoCollection.insertOne(Document.parse(sampleRecording))
    }

    @AfterEach
    public clearDb(){
        mongoCollection.drop()
    }
}
}

0 个答案:

没有答案