斯波克测试框架 - 如何参数化@Rule资源?



我正在更新一个斯波克测试。很少有模拟和@Rule资源:

AuthTokenService mockAuthTokenService = Mock()
ObjectMapper mockObjectMapper = Mock()
GeneralConfiguration conf = Mock();
def CLA_BASE_URL = "http://some-prefix/";
@Rule
ResourceTestRule resource = ResourceTestRule.builder()
.addResource(new AuthResourceImpl(mockAuthTokenService, mockObjectMapper, conf))
.build()

我需要资源为两个不同的测试提供不同的conf。所以我尝试了

def 'create auth token with configured URL prefix'() {
setup:
AuthTokenMetaData authTokenMetaData = buildAuthTokenMetaData()
when:
conf.getClaBaseUrl() >> CLA_BASE_URL
...

但这不起作用,因为resource创建一次。 所以我不得不添加另一个资源。

GeneralConfiguration conf2 = new GeneralConfiguration().setClaBaseUrl(CLA_BASE_URL);
@Rule
ResourceTestRule resource2 = ResourceTestRule.builder()
.addResource(new AuthResourceImpl(mockAuthTokenService, mockObjectMapper, conf2))
.build()

但这感觉有点奇怪,从与斯波克的短暂接触来看,我相信它有一些更好的方法。

如何参数化ResourceTestRule

它必须是 JUnit 规则,因为ResourceTestRule的基础实现。

> Spock 没有提供任何参数化@Rule的机制,因为规则是在数据驱动特征被执行之前创建的。

正如伦纳德所提到的,Spock 只是一个 JUnit,它支持与 JUnit 相同的@Rule机制,因此没有特殊的语法。

因此,如果您需要两种不同的配置,您可能应该使用两种不同的规则定义,并根据测试的"时髦性"提出最适合您的解决方案:

下面是一个例子:

class FirstConfigurationSpecification extends Specification {
@Rule // config A
}
class SecondConfigurationSpecification extends Specification {
@Rule // config B
}
// in tests
class MyTestThatRequiresConfigurationA extends FirstConfigurationSpecification {}
// in tests
class MyTestThatRequiresConfigurationB extends SecondConfigurationSpecification {}

最新更新