0

我正在更新 Spock 测试。很少有模拟和@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()

但这感觉有点奇怪,而且从与 Spock 的短暂接触中,我相信它有更好的方法来解决这个问题。

如何参数化ResourceTestRule

它必须是 JUnit 规则,因为ResourceTestRule.

4

2 回答 2

1

Spock 不提供任何参数化 a 的机制@Rule,因为规则是在执行数据驱动功能之前创建的。

于 2018-09-01T15:36:35.477 回答
0

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

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

这是一个例子:

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 {}
于 2018-09-03T04:20:11.750 回答