【问题标题】:How to read variable from application.yml with spring boot and use it in kotlin test如何使用 spring boot 从 application.yml 读取变量并在 kotlin 测试中使用它
【发布时间】:2019-02-11 14:17:08
【问题描述】:
src
  main
    java
       config
          DataSourceProperties.java
    resources
      application.yml
  test
    kotlin
      service
          AuthService.kt
  1. 我有 application.yml Image of application.yml file
  2. 我有java配置类

     @Configuration
     @ConfigurationProperties(prefix = "datasource")
    class DataSourceProperties {
       private String apiUrl;
       public String getApiUrl() { return apiUrl; }
       public void setUrl(String apiUrl) {
          this.apiUrl = apiUrl;
    }
    
  3. 我有服务 kotlin 类

     @RunWith(SpringRunner::class)
     @SpringBootApplication
     @Profile("dev")
     class AuthService {
       @Value("\${datasource.apiUrl}")
       lateinit var apiUrl: String
       fun registerUser(user: RequestUser): ErrorResponse {
        return given()
                .log().all()
                .body(user)
                .contentType(ContentType.JSON)
                .`when`().post("$apiUrl/security")
                .then().statusCode(StatusCodes.BAD_REQUEST)
                .extract()
                .`as`(ErrorResponse::class.java)
        }
    }
    

当我在测试中执行请求时,我得到

kotlin.UninitializedPropertyAccessException:lateinit 属性 apiUrl 尚未初始化

这就是我有疑问的原因?如何在测试类中使用 yml 文件中的属性。也许我错过了另一个配置,也许我对注释不正确,或者它取决于结构中配置、yml 和测试文件的位置。请给我一个提示。

【问题讨论】:

  • 调查一些材料:如果它位于主文件夹中,我可以启动 java 测试类。但是当我将测试类重新定位到测试文件夹时它失败了。

标签: java spring-boot kotlin yaml


【解决方案1】:

尝试简单设置,例如应该帮助 - @TestPropertySource(properties = ["spring.mail.properties.mail.smtp.auth: false", "spring.mail.properties.mail.smtp.starttls.enable: false"])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-25
    • 2015-03-18
    相关资源
    最近更新 更多