【问题标题】:How can I access a globally defined property that is accessed through a property file using Spock when unit testing如何在单元测试时使用 Spock 访问通过属性文件访问的全局定义的属性
【发布时间】:2021-05-14 21:16:30
【问题描述】:

我正在尝试对一种方法进行单元测试,该方法使用从使用@Value 注释的属性文件派生的全局定义变量。如何在单元测试中访问服务类中的这个全局属性,而无需将其传递给方法签名。

例如: 名为“SampleService”的 Spring Boot 服务

@Value("${sampleproperty.value}")
private String sampleProperty;

private sampleMethodName(){
     //method which uses the global variable 'sampleProperty'
}

Spock 测试示例

def "Unit Test"(){
    given:
       //ToDo
    when:
       sampleService.sampleMethodName() //How to access the 'sampleProperty'
    then:
       //ToDo
}

【问题讨论】:

    标签: java spring-boot unit-testing groovy spock


    【解决方案1】:

    在 Spock 和 groovy 测试中,您可以在任何地方通过变量名访问私有变量

    def "Unit Test"(){
    given:
       sampleService.sampleProperty = "value"  //to set the value
       //ToDo
    when:
       sampleService.sampleMethodName() //How to access the 'sampleProperty'
    then:
       //ToDo
       sampleService.sampleProperty == "value" //to access the value
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多