简体   繁体   English

经典的单元测试作为Groovy Spock方法

[英]Classical unit test as Groovy Spock method

I have a Groovy Spock method that has the following pattern: 我有一个具有以下模式的Groovy Spock方法:

def "My test"() {
  def a = createA();
  assert a.fieldLevel1.isValid()
  def b = a.fieldLevel1
  assert b.fieldLevel2.isValid()
  def c = b.fieldLevel2
  assert c.fieldLevel3.isValid()
  ...
}

As you can see it's hard to break it on blocks as assertions and variables definitions are mixed together. 如您所见,由于断言和变量定义混合在一起,很难在块上打破它。 What would be the "spock" approach to write such kind of test? 编写此类测试的“ spock”​​方法是什么?

UPDATE: 更新:

The test has the following structure because c.fieldLevel3.isValid() is actually c.fieldLevel3 instanceof A , so I can't proceed if the field is invalid. 该测试具有以下结构,因为c.fieldLevel3.isValid()实际上是c.fieldLevel3 instanceof A ,因此如果该字段无效,则无法继续进行。

The "classical" way of unit testing is keeping tests unitary. 单元测试的“经典”方式是保持测试统一。 That is, testing one thing per test, which seems not to be the case in this example. 也就是说,每个测试只测试一件事 ,在本示例中似乎并非如此。

That being said, however, you could group all the assertions in an expect block after all the setup code in a setup block: 话虽这么说,但是,你能集团所有的断言expect之后的所有设置代码块setup块:

def "My test"() {
  setup:
  def b = createA().fieldLevel1
  def c = b.fieldLevel2
  def d = c.fieldLevel3
  expect:
  b.valid
  c.valid
  d.valid
}

Notice that i've shortened the assertions by using Groovy's goodies to access isValid() as valid and calling that method on the auxiliary objects directly. 注意,我通过使用Groovy的好东西访问isValid() valid并直接在辅助对象上调用该方法来缩短了断言。

Also, i haven't used the usual when/then Spock blocks because this test case doesn't seems to align very well with being a stimuli/response on a given system. 另外,我没有使用通常的when/then Spock块,因为此测试用例似乎与给定系统上的刺激/响应不太吻合。 But you could also use many when and then alternated blocks if you so desire: 但是,如果您愿意,也可以使用很多when块, then交替块:

def "My test"() {
  when: def b = createA().fieldLevel1
  then: b.valid
  when: def c = b.fieldLevel2
  then: c.valid
  when: def d = c.fieldLevel3
  then: d.valid
}

Not sure why you did not accept the answer above it looks quite good. 不知道为什么您不接受上面的答案,它看起来还不错。

As a minor difference, you could also do: 作为一个小差异,您还可以执行以下操作:

def "My test of creating an A"() {
    when: 
        def a = createA()
    then: 
        a.fieldLevel1.isValid()
        a.fieldLevel1.fieldLevel2.isValid()
        a.fieldLevel1.fieldLevel2.fieldLevel3.isValid()
}

Whether or not you 'like' this depends upon how closely you follow Demeter's 'Law' - Groovy seems to make that less relevant than in the past. 是否“喜欢”这取决于您对Demeter的“法律”的关注程度-Groovy似乎与过去相比没有那么重要了。

If the complexity of the actual underlying objects is such that this is not an effective approach at validating them, then they might deserve their own Unit Tests. 如果实际基础对象的复杂性使得这不是验证它们的有效方法,那么它们可能应该进行自己的单元测试。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM