我已经使用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块返回?
HttpServletRequest mockHttpRequest = Mock()
移动到测试开始处的setup
块吗? - tim_yates@Shared
类级别字段中。 - tim_yates@Shared
注解,但正如其中一个答案所说:“缺点是 a 和 o 在某种意义上在错误的作用域中定义,并且也可能被其他特性方法使用。”正如我在我的编辑中所说的那样,这对我来说似乎是不好的实践,但如果没有其他选择,我将不得不研究它。 - Ben Green