Public groovy 方法必须是 public,编译器说

Public groovy method must be public, says the compiler

此错误的原因是什么,我该如何解决?

乍一看,这似乎是 groovy 编译器的缺陷。

:compileIntegrationTestGroovystartup failed:
C:\src\my-project\src\integration-test\groovy\my\project\MyServiceISpec.groovy: 31: The method setup should be public as it implements the corresponding method from interface my.project.MyTrait
. At [31:5]  @ line 31, column 5.
       public void setup() {
       ^

1 error

我的 grails 集成测试如下所示:

@Integration
@Rollback
class MyServiceISpec extends Specification implements MyTrait {
    @Autowired
    MyService service

    OtherService otherService = Mock()

    public void setup() {
        myTraithMethod()
        service.otherService = otherService
    }
}

我的性格是这样的:

trait MyTrait {
    public void setup() {
        myTraithMethod()
    }

    private myTraitMethod() {
        ...
    }
}

更新 添加 public 关键字到特征设置方法。

1/ 不确定,但特征名称是 ResetsDatabase 并且您的测试实现了 MyTrait。 可能与特征有些混淆? 2 / 在我看来,如果您的特征表明该方法(此处设置)是私有的,那么您不能在已实现的方法上使用 public 方法。

我认为这个问题的根源是 AST,因为 Spock 使用 AST 转换并编译规范。你可以在这里阅读 http://docs.groovy-lang.org/next/html/documentation/core-traits.html#_compatibility_with_ast_transformations 这个:

Traits are not officially compatible with AST transformations. Some of them, like @CompileStatic will be applied on the trait itself (not on implementing classes), while others will apply on both the implementing class and the trait. There is absolutely no guarantee that an AST transformation will run on a trait as it does on a regular class, so use it at your own risk!

您可以通过重命名 traitSetup() 特征中的 setup() 方法来解决它,例如,并从规范 setup() 方法中调用它,如下所示:

@Integration
@Rollback
class MyServiceISpec extends Specification implements MyTrait {
    @Autowired
    MyService service
    OtherService otherService = Mock()

    void setup() {
        service.otherService = otherService
        traitSetup()
    }

    def 'some test here'() {
        ...
    }
}

trait MyTrait {
    void traitSetup() {
        myTraitMethod()
    }

    private myTraitMethod() {
        ...
    }
}