groovy - def 与 Groovy 中的最终 def

标签 groovy spock

我已经使用 Spock frameworkGroovy 中编写了简单的测试

class SimpleSpec extends Specification {

    def "should add two numbers"() {
        given:
            final def a = 3
            final b = 4
        when:
            def c = a + b
        then:
            c == 7
    }
}

变量 a 使用 deffinal 关键字组合声明。变量 b 仅使用 final 关键字声明。

我的问题是:这两个声明之间有什么区别(如果有)?是否应该优先考虑一种方法?如果是这样,为什么?

最佳答案

用户daggett是对的,final不会在Groovy中将局部变量设为final。关键字仅对类成员有影响。这是一个小说明:

package de.scrum_master.stackoverflow

import spock.lang.Specification

class MyTest extends Specification {
  def "Final local variables can be changed"() {
    when:
    final def a = 3
    final b = 4
    final int c = 5
    then:
    a + b + c == 12

    when:
    a = b = c = 11
    then:
    a + b + c == 33
  }

  final def d = 3
  static final e = 4
  final int f = 5

  def "Class or instance members really are final"() {
    expect:
    d + e + f == 12

    when:
    // Compile errors:
    // cannot modify final field 'f' outside of constructor.
    // cannot modify static final field 'e' outside of static initialization block.
    // cannot modify final field 'd' outside of constructor.
    d = e = f = 11
    then:
    d + e + g == 33
  }
}

当我使用 Groovy 2.5 将 Spock 项目之一切换到版本 1.3 时,注意到由于编译器检测到对最终局部变量的重新分配,该测试现在不再编译。 IE。 Groovy <= 2.4 中的不一致似乎已得到修复。

关于groovy - def 与 Groovy 中的最终 def,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50645835/

相关文章:

Groovy:有没有在参数拷贝后调用的构造函数?

groovy - 将 Groovy 模板引擎与大型 (>64k) 模板一起使用

groovy - 使用 GroovyShell 从 Gradle 运行 Groovy 脚本 : Exception in thread "main" java. lang.NoClassDefFoundError: org/apache/commons/cli/ParseException

java - 为什么 stash/unstash 在此 Jenkinsfile 中不起作用?

unit-testing - 从 grails 2.3 升级到 2.5 后单元测试无法运行

java - Spock + Spring Boot Web - 获取异常消息

jenkins - 如何在 Jenkins 声明式管道中创建方法?

unit-testing - 为什么即使使用 Spocks 的 Mock() 模拟了底层 Controller ,此方法仍返回 null?

java - 使用 Spring Boot 和 Spock 进行集成测试

java - 如何模拟带注释的类?