3

我正在尝试将在 spring 上下文中配置的规则注入到 spock 规范中。


@ContextConfiguration(locations=["spring.xml"])
class TestSpec extends Specification {
    @Rule @Inject //@Autowired
    public ActivitiRule activitiRule;

    @Deployment
    def "Process test"() {
    when:
    //...
    then:
    //...
    }
}

问题是 spock 自己实例化规则而不考虑@Injector@Autowired注释。在 JUnit 中,这按预期工作。是否可以将规则注入 spock?

4

2 回答 2

1

只要这不能开箱即用(请参阅问题),我发现一个可能的解决方法是使用 Spring TestExecutionListener 而不是 TestRule,这当然只有在您自己编写规则时才有用。

在 TestExecutionListener 中,您可以访问 ApplicationContext 并且可以获得您需要的任何 bean。

于 2013-07-10T17:48:43.223 回答
1

有趣的用例。问题是 Spock 的 Rule 扩展在 Spock 的 Spring 扩展注入规则之前调用了该规则。有可能解决这个问题。如果您不介意,请在http://issues.spockframework.org提交问题。目前,只有注入MethodRules(而不是TestRules)才能按预期工作。

于 2013-07-09T22:46:10.707 回答