Spock으로 grails 단위 테스트를 수행 할 때 도메인에 서비스 인스턴스를 자동 삽입 할 수 없습니다.Grails Spock으로 테스트 할 때 도메인에 서비스를 삽입 할 수 없습니다.
아래 코드는 제 코드입니다.
서비스 :
class HiService {
public HiService(){
println "Init HiService," + this.toString()
}
def sayHi(String name){
println "Hi, ${name}"
}
}
도메인 :
class User {
public User(){
if (hiService == null){
println "hiService is null when new User(${name})"
}
}
String name
def hiService
def sayHi(){
println "Before use hiService " + hiService?.toString()
hiService.sayHi(name)
println "End use hiService" + hiService?.toString()
}
}
의 TestCase :
다음
@TestFor(HiService)
@Mock([User])
class HiServiceTest extends Specification {
def "test sayHi"() {
given:
def item = new User(name: "kitty").save(validate: false)
when: "Use service method"
item.sayHi()
then : "expect something happen"
assertEquals(1, 1)
}
}
--Output from test sayHi--
Init HiService,[email protected]
hiService is null when new User(null)
Before use hiService null
| Failure: test sayHi(test.HiServiceTest)
| java.lang.NullPointerException: Cannot invoke method sayHi() on null object
\t at test.User.sayHi(User.groovy:17)
\t at test.HiServiceTest.test sayHi(HiServiceTest.groovy:20)
하지만 도메인에 삽입 할 수 없습니다. 하지만 앱을 직접 실행하면 도메인에 서비스가 자동 삽입됩니다.
당신은'주어진에'item.hiService = service'을 필요 사양 {
}을 확장합니다. – dmahapatro
@dmahapatro 감사합니다 – cyj
@dmahapatro @dmahapatro 수동으로 도메인의 초기화 서비스는 단위 테스트를 할 때 편리하지 않습니다. 왜냐하면 각 도메인은 여러 서비스를 사용할 수 있기 때문에 각 단위 테스트에서 다중 도메인을 사용할 수 있습니다. 이 문제를 해결 하시겠습니까? – cyj