代码之家  ›  专栏  ›  技术社区  ›  Ondra Žižka David Lilljegren

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

  •  0
  • Ondra Žižka David Lilljegren  · 技术社区  · 6 年前

    @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规则,因为 资源测试规则

    2 回复  |  直到 6 年前
        1
  •  0
  •   Mark Bramnik    6 年前

    正如Leonard提到的,Spock只是一个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 {}
    
        2
  •  1
  •   Leonard Brünings    6 年前

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

    推荐文章