gpt4 book ai didi

unit-testing - 在阻止的 spock 测试中抛出 MissingPropertyException

转载 作者:行者123 更新时间:2023-12-04 05:15:38 25 4
gpt4 key购买 nike

我一直在使用 spock 对我的 java 项目进行单元测试,但遇到了问题。我有一个实用方法可以从 http 请求中获取参数,或者如果 http 请求为空并尝试用 spock 测试它,则为空字符串。我的测试是这样的:

package foo.bar.test

import foo.bah.HttpRequestPropertyLoader
import spock.lang.Unroll
import javax.servlet.http.HttpServletRequest
import spock.lang.Specification

class HttpRequestPropertyLoaderTest extends Specification {

HttpRequestPropertyLoader subjectUnderTest
def result

def setup() {
subjectUnderTest = new HttpRequestPropertyLoader()
}

@Unroll("When my http request is #nullOrNot then when I get parameter from it the response=#response" )
def "Test load data from request"() {
given:
HttpServletRequest mockHttpRequest = Mock()
mockHttpRequest.getAttribute("foo") >> "bar"
when:
result = subjectUnderTest.loadStringFromHttpRequest(httpRequest, "foo")
then:
result == response
where:
httpRequest | response | nullOrNot
null | "" | "null"
mockHttpRequest | "bar" | "not null"
}
}

但是,当我运行此测试时,出现以下错误:
groovy.lang.MissingPropertyException: No such property: mockHttpRequest for class: foo.bar.test.HttpRequestPropertyLoaderTest at foo.bar.test.HttpRequestPropertyLoaderTest.Test load data from request(HttpRequestPropertyLoaderTest.groovy)
经过一番研究,我了解到 where块在 given 之前运行块,因此出现错误,但只是想知道是否有解决方法?

我知道要使用测试外部的变量,我需要用 @Shared 注释该变量。注释,这对我来说似乎是不好的做法。每个测试都应该与其他测试完全分开运行,所以不要真的想要一个对象来保持它在测试之间的状态。

是否可以将 Mock 对象设置为以其他方式从 where 块返回?

最佳答案

按照 tim_yates 建议查看 https://code.google.com/p/spock/issues/detail?id=15#c4 ,我找到了一个相当优雅的解决方案,它不涉及使用 @Shared注解。测试定义现在看起来像这样:

package foo.bar.test

import foo.bah.HttpRequestPropertyLoader
import spock.lang.Unroll
import javax.servlet.http.HttpServletRequest
import spock.lang.Specification

class HttpRequestPropertyLoaderTest extends Specification {

HttpRequestPropertyLoader subjectUnderTest
def result

def setup() {
subjectUnderTest = new HttpRequestPropertyLoader()
}

@Unroll("When my http request is #nullOrNot then when I get parameter from it the response=#response" )
def "Test load data from request"() {
when:
result = subjectUnderTest.loadStringFromHttpRequest(httpRequest, "foo")
then:
result == response
where:
httpRequest << {
HttpServletRequest mockHttpRequest = Mock()
mockHttpRequest.getAttribute("foo") >> "bar"
[null, mockHttpRequest]
}()
response << ["", "bar"]
nullOrNot << ["null", "not null"]
}
}

关于unit-testing - 在阻止的 spock 测试中抛出 MissingPropertyException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31473809/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com