groovy 如何重用测试的某些部分?

unftdfkk  于 4个月前  发布在  其他
关注(0)|答案(4)|浏览(62)

我需要实现以下逻辑:
1.做点什么
1.检查逻辑
1.做点别的
1.相似校验逻辑
我使用when/then块进行简单的测试。但我真的不知道如何实现更复杂的一个(如上所述)+我想尽可能多地重用代码。但与块它变得更复杂的实现

nle07wnf

nle07wnf1#

我在Spock中采用了几种方法来重用代码。

特性级别在setup:block中创建一个闭包,你可以将它当作一个方法,只对这个特性可用。

def "test"() {
    setup:
        def containsCat = {String it -> it.contains('cat')}
    expect:
        !containsCat('I love my dog')
        containsCat('I love my cat')
}

def "test that cannot reference containsCat(String)"() {
    // Test stuff
}

字符串

Spec Class Level虽然可以使用@Shared闭包,但我更喜欢使用私有helper方法,除非helper逻辑只有一两行。

class tester extends Specification {
@Shared
def containsDog = {String it -> it.contains('dog')}
private containsCat(String inputString) {
    inputString.contains('cat')
}

def "test"(String myPet) {
    expect: containsCat(myPet)
    where: myPet = 'I love my cat'
}

def "test2"() {
    expect: containsDog(mySistersPet)
    where: mySistersPet = 'I love my dog'
}

套餐级别

我有一组类,它们都可以从共享一个微型测试框架中受益。我的偏好是使用trait。它们可以包含除了特性测试本身之外的任何代码。如果trait将引用来自测试本身的数据,请确保创建一个抽象方法,以便确保trait引用数据。

trait petTester {
    private containsDog(String inputString) {
        inputString.contains('dog')
    }    
    private containsCat(String inputString) {
        inputString.contains('cat')
    }    
}

class myPetTester extends Specification implements petTester {
    def "test"(String myPet) {
        expect: containsCat(myPet)
        where: myPet = 'I love my cat'
    }
}

class mySistersPetTester extends Specification implements petTester {
    def "test2"() {
        expect: containsDog(mySistersPet)
        where: mySistersPet = 'I love my dog'
    }    
}

iyfjxgzm

iyfjxgzm2#

如果你想运行相同的测试两次,只是改变一些参数,你可以使用where

def "foo"(Boolean barIsEnabled) {
      when:
      myService.testBar(barIsEnabled)

      then:
      myService.readBar() == "123456"

      where: "this code shoud work with bar enabled or disabled"
      barIsEnabled  | ignored
      true          | _
      false         | _
  }

字符串
参考号:http://spockframework.github.io/spock/docs/1.0/data_driven_testing.html
如果你只是想重用then逻辑,创建一个私有方法,并在其中添加许多assert

def "foo"() {
  when:
  def pc = shop.buyPc()

  then:
  matchesPreferredConfiguration(pc)
}
void matchesPreferredConfiguration(pc) {
  assert pc.vendor == "Sunny"
  assert pc.clockRate >= 2333
  assert pc.ram >= 4096
  assert pc.os == "Linux"
}


参考:http://spockframework.github.io/spock/docs/1.0/spock_primer.html#_helper_methods

41ik7eoe

41ik7eoe3#

你也可以使用interaction { doStuff() }
然而,如果你发现你的doStuff()很大,并且你的许多测试都使用相同的交互方法,那么可能是时候考虑将生产类中的一些代码移动到一个单独的类中,然后有一个期望,即你的测试类调用你的新类。

n1bvdmb6

n1bvdmb64#

Spock文档中的例子非常好,但奇怪的是对我来说不太有效。https://spockframework.org/spock/docs/1.0/spock_primer.html#_helper_methods
我需要将\添加到他们的示例中

def matchesPreferredConfiguration(pc) {
  pc.vendor == "Sunny" \
  && pc.clockRate >= 2333 \
  && pc.ram >= 4096 \
  && pc.os == "Linux"
}

字符串

相关问题