Spock测试向grailsApplication注入null,因为我尝试自动连接grails服务和域对象(spec)
码(AttackSpec.groovy)
package core
import grails.test.mixin.TestFor
import grails.test.mixin.TestMixin
import grails.test.mixin.support.GrailsUnitTestMixin
import spock.lang.Specification
/**
* See the API for {@link grails.test.mixin.domain.DomainClassUnitTestMixin} for usage instructions
*/
@TestMixin(GrailsUnitTestMixin)
@TestFor(Attack)
class AttackSpec extends Specification {
def grailsApplication
def setup() {
Attack attack = new Attack();
println 'app '+grailsApplication.toString()
}
def cleanup() {
}
void "test something"() {
setup:
println 'app '+grailsApplication.toString()
}
}
输出
log4j:WARN No appenders could be found for logger (org.codehaus.groovy.grails.commons.DefaultGrailsApplication).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
appnull
appnull
SLF4J: Class path contains multiple SLF4J bindings.
SLF4J: Found binding in [jar:file:/C:/ops/grails-2.4.4/dist/grails-plugin-log4j-2.4.4.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: Found binding in [jar:file:/C:/ops/grails-2.4.4/lib/org.slf4j/slf4j-simple/jars/slf4j-simple-1.7.5.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: See http://www.slf4j.org/codes.html#multiple_bindings for an explanation.
SLF4J: Actual binding is of type [org.slf4j.impl.GrailsSlf4jLoggerFactory]
我尝试使用显式的@Autowired注释和静态类型,但它总是一样的。好像我必须在某处给grails应用程序充气?
答案 0 :(得分:2)
听起来你想要运行集成测试而不是单元测试。在集成测试文件夹下移动您的类,您可能需要删除测试类注释,因为我认为这些仅用于单元测试。
答案 1 :(得分:1)
在单元测试中注入grailsApplication
有什么意义?如果你想设置一个配置,因为你的测试类:Attack
读取grails应用程序的值,那么你可以按如下方式模拟grailsApplication:
def 'test whatever you want to'() {
def attack = new Attack()
attack.grailsApplication = [config: [my: [setting: "myValue"]]] // if attack uses grailsApplication.config.my.setting internally
when:
def setting = attack.getMySetting()
then:
setting == "myValue"
}
如果你想跟踪对它的访问,你可以使用真正的模拟。
如果您确实想要使用grails环境进行测试,那么对框架上的值的访问(无论出于何种原因)是正确执行的,您应该使用集成测试。从Spock子类化IntegrationSpec会将grailsApplication注入到您的测试中,因此您可以在Attack
类中设置真实内容。