2017-08-16 58 views
1

我試圖建立一個春天啓動JUnit測試與嵌入式蒙戈&卡夫卡: -春天引導與嵌入式蒙戈:無法分配請求的地址:JVM_Bind

@RunWith(SpringRunner.class) 
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.NONE, 
     classes = {AccountingApplication.class}) 
@DataMongoTest 
public class BaseEmbeddedTest { 


    @ClassRule 
    public static KafkaEmbedded embeddedKafka = new KafkaEmbedded(1, true); 

    @Autowired 
    private MongoTemplate mongoTemplate; 


    @Test 
    public void emptyTest(){ 

    } 

} 

的src /測試/資源/應用.yml: -

spring: 
    data: 
    mongodb: 
     port: 0 
    kafka: 
    bootstrap-servers: ${spring.embedded.kafka.brokers} 

問題

Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [de.flapdoodle.embed.mongo.config.IMongodConfig]: Factory method 'embeddedMongoConfiguration' threw exception; nested exception is java.net.BindException: Cannot assign requested address: JVM_Bind 
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:189) 
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:588) 
    ... 140 more 
Caused by: java.net.BindException: Cannot assign requested address: JVM_Bind 
    at java.net.DualStackPlainSocketImpl.bind0(Native Method) 
    at java.net.DualStackPlainSocketImpl.socketBind(DualStackPlainSocketImpl.java:106) 
    at java.net.AbstractPlainSocketImpl.bind(AbstractPlainSocketImpl.java:387) 
    at java.net.PlainSocketImpl.bind(PlainSocketImpl.java:190) 
    at java.net.ServerSocket.bind(ServerSocket.java:375) 
    at java.net.ServerSocket.<init>(ServerSocket.java:237) 
    at de.flapdoodle.embed.process.runtime.Network.getFreeServerPort(Network.java:80) 
    at org.springframework.boot.autoconfigure.mongo.embedded.EmbeddedMongoAutoConfiguration.embeddedMongoConfiguration(EmbeddedMongoAutoConfiguration.java:147) 

我在這裏做錯了什麼?

版本: -

dependencyManagementPluginVersion = '1.0.3.RELEASE' 
    springBootVersion = '1.5.6.RELEASE' 
    springCloudVersion = 'Dalston.SR2' 
    projectVersion = '0.0.1-SNAPSHOT' 
    javaVersion = 1.8 
    kotlinVersion = '1.1.4' 

回答

1

此註釋:@DataMongoTest導致春季啓動創建一個嵌入蒙戈實例。異常消息告訴我們,嵌入式Mongo實例無法啓動,因爲已經有一個進程在運行的端口上運行。

嵌入式蒙戈實例被EmbeddedMongoAutoConfiguration配置和春季啓動應用的策略 - 爲端口分配 - 如下:

if configured Mongo port > 0 then 
    use the configured port 
else 
    assign a random port 
end 

所以,我懷疑你的測試範圍內配置有非零值爲spring.data.mongodb.port。我知道你發佈了你的application.yml,這意味着你正確地指定了一個零值給spring.data.mongodb.port,但是如果你在EmbeddedMongoAutoConfiguration構造函數中放置了一個斷點,並且在屬性參數中查看了內容,我想你會看到實際使用的值通過該配置類不是零。如果傳遞給EmbeddedMongoAutoConfiguration的端口值實際上爲零,但您仍然收到JVM_Bind錯誤,那意味着此調用:Network.getFreeServerPort(this.getHost())未返回空閒端口,這似乎不太可能。

爲了解決這個問題:只要你用spring.data.mongodb.port=0配置你的測試上下文,那麼嵌入式Mongo實例將被分配一個隨機端口,並且這個隨機端口將會讓你的Spring上下文的其他方面知道(比如您的MongoTemplate)需要與該Mongo實例交談。

相關問題