Spock测试框架 - 如何参数化@Rule资源?

问题描述 投票:0回答:2

我正在更新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的底层实现。

groovy mocking spock junit-rule
2个回答
0
投票

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

因此,如果您需要两种不同的配置,您应该使用两种不同的规则定义,并根据测试的“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 {}

1
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.