代码之家  ›  专栏  ›  技术社区  ›  switch201

T

  •  0
  • switch201  · 技术社区  · 7 年前

    我的示例脚本如下所示:

    @Stepwise
    class RandomTest extends GebReportingSpec {
    
    
        @Shared
        Random random = new Random()
        def tag = random.nextInt(999)+1
    
        def setupSpec() {
            new File('/ProgramData/geb.properties').withInputStream {
                properties.load(it)
            }
        }
    
        def "Random Test"(){
            when:
            println("Random1: ${tag}")
            println("Random2: ${tag}")
            then:
            Thread.sleep(1000)
        }
    
        def "Random test2"(){
            when:
            println("Random3: ${tag}")
            then:
            Thread.sleep(1000)
        }
    }
    

    Random1: 528
    Random2: 528
    Random3: 285
    

    我假设这是因为共享变量是在特征方法之间重新计算的。我已经尝试将这些变量声明移到 @Shared 注释无效。

    我希望随机标记变量在规范的开头生成,并且我希望它保留其值,但是我不确定如何设置全局变量来实现这一点。我需要实例化setupSpec中的变量吗?

    2 回复  |  直到 7 年前
        1
  •  2
  •   Michael    7 年前

    @Shared 变量是 在测试之间重新评估。你观察的原因是你输出的不是 @共享 变量 tag . random.nextInt(999)+1

    如果你放一个 标签 值不会改变。

        2
  •  0
  •   switch201    7 年前

    @Shared
    def tag
    def setupSpec() {
        new File('/ProgramData/geb.properties').withInputStream {
            properties.load(it)
        }
        Random random = new Random()
        tag = random.nextInt(999)+1
    }
    
    def "Random Test"(){
        when:
        println("Random1: ${tag}")
        println("Random2: ${tag}")
        then:
        Thread.sleep(1000)
    }
    
    def "Random test2"(){
        when:
        println("Random3: ${tag}")
        then:
        Thread.sleep(1000)
    }