2017-09-27 23 views
0

我有一個特殊的性能測試資源目錄中的文件爲什麼spring boot首先在測試資源中不使用application.properties?

└── test 
    ├── java 
    │ └── com 
    │  └── inter3i 
    │    ├── dao 
    │    │ └── FooMapperTest.java 
    └── resources 
     └── application.properties 
在此

的application.properties文件我指定的MySQL URL。

spring.datasource.url=jdbc:mysql://139.224.xxx.xxx/foo?useSSL=false 

然後我執行測試

mvn test -Dtest=com.foo.reportapi.dao.FooMapperTest 

但失敗了,因爲

org.springframework.transaction.CannotCreateTransactionException: Could not open JDBC Connection for transaction; nested exception is com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure 

The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server. 
    at org.springframework.jdbc.datasource.DataSourceTransactionManager.doBegin(DataSourceTransactionManager.java:289) ~[spring-jdbc-4.3.10.RELEASE.jar:4.3.10.RELEASE] 

但實際上MySQL的URK是確定的,爲什麼它有這樣的錯誤?從Wireshark的我知道它實際連接到另一個URL

spring.datasource.url=jdbc:mysql://192.168.0.25/foo 

application-default.properties

src 
├── main 
│ └── resources 
│  ├── application-default.properties 

配置那麼,爲什麼會這樣有悖常理?我認爲測試類首先應該在測試資源中使用application.properties

此外,我必須使用wireshark來查找它連接到哪個URL,我怎麼能得到Spring Boot明確輸出MySQL URL信息?

+1

每https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html'應用程序 - {profile}'比'application'具有更高的優先級。 – jonrsharpe

回答

0

正如jonrsharpe已經提到的,特定的輪廓具有在application.properties文件的優先級 - 在這裏你找到PropertySource秩序的文件:

https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html

您可以修復它在serveral的方式:

  1. 將main/resources/application-default.properties重命名爲main/resources/application.properties
  2. 將test/resources/application.propertie重命名爲s to test/resources/application-default.properties
  3. 將test/resources/application.properties重命名爲test/resources/application-default-integrationtest.properties並在您的測試類上啓用具有以下注釋的配置文件:@ActiveProfiles( {「integrationtest」})

我會推薦#3,因爲它不依賴於主要和測試元素的類路徑優先級,並明確指出使用哪個文件。

現在到您的問題的日誌記錄部分。

如果將彈簧日誌級別增加到「調試」,您可以看到加載了哪些配置文件。你可以在自己的代碼登錄一個特定的屬性:

@Component 
@Slf4j 
public class LogSpringDatasourceUrlProperty { 
    @Autowired 
    public LogSpringDatasourceUrlProperty(@Value("${spring.datasource.url}") String jdbcUrl){ 
    log.info("application uses '{}' as jdbcUrl", jdbcUrl);  
    } 
} 
相關問題