【发布时间】:2015-11-04 18:53:13
【问题描述】:
我试图在运行when-then-where 形式的多个测试用例的单个 Spock 方法的上下文中验证两个不同的输出。出于这个原因,我在then 块中使用了两个断言,如下例所示:
import spock.lang.*
@Unroll
class ExampleSpec extends Specification {
def "Authentication test with empty credentials"() {
when:
def reportedErrorMessage, reportedErrorCode
(reportedErrorMessage, reportedErrorCode) = userAuthentication(name, password)
then:
reportedErrorMessage == expectedErrorMessage
reportedErrorCode == expectedErrorCode
where:
name | password || expectedErrorMessage | expectedErrorCode
' ' | null || 'Empty credentials!' | 10003
' ' | ' ' || 'Empty credentials!' | 10003
}
}
代码是一个示例,其中设计要求是如果name 和password 是' ' 或null,那么我应该总是期望完全相同的expectedErrorMessage = 'Empty credentials!' 和expectedErrorCode = 10003。如果由于某种原因(可能是由于源代码中的错误)我得到expectedErrorMessage = Empty!(或'Empty credentials!' 以外的任何其他内容)和expectedErrorCode = 10001(或1003 以外的任何其他内容),这将不满足上述条件要求。
问题是,如果两个断言在同一测试中失败,我只会收到第一个断言的失败消息(这里是reportedErrorMessage)。是否可以在同一个测试中获得所有失败的断言的通知?
这里有一段代码演示了同样的问题,没有其他外部代码依赖。我知道在这种特殊情况下,将两个非常不同的测试捆绑在一起并不是一个好习惯,但我认为它仍然说明了问题。
import spock.lang.*
@Unroll
class ExampleSpec extends Specification {
def "minimum of #a and #b is #c and maximum of #a and #b is #d"() {
expect:
Math.min(a, b) == c
Math.max(a, b) == d
where:
a | b || c | d
3 | 7 || 3 | 7
5 | 4 || 5 | 4 // <--- both c and d fail here
9 | 9 || 9 | 9
}
}
【问题讨论】:
-
在您提供的 mongo 测试中,它也会依次失败。
-
两个 cmets:1) 您是否能够创建一个测试来演示此问题而无需任何其他外部代码依赖项? 2) 为什么你的
where块中有一个双管 (||)?这不是我认为应该使用的格式。 -
@mnd,见here。
||完全有效。 -
您希望它在测试中运行所有断言,即使第一个断言失败?
-
@Opal 你说得对,谢谢你告诉我。
标签: testing groovy automated-tests spock