2017-01-07 2 views
0

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)
서비스가 초기화

하지만 도메인에 삽입 할 수 없습니다. 하지만 앱을 직접 실행하면 도메인에 서비스가 자동 삽입됩니다.

+0

당신은'주어진에'item.hiService = service'을 필요 사양 {

def "User is able to say hi"() { given: User user = new User(name: 'bla bla') and: "Mock the user service" def hiService = Mock(HiService) user.hiService = hiService when: user.sayHi() then: 1 * sayHiService.sayHi(user.name) } 

}을 확장합니다. – dmahapatro

+1

@dmahapatro 감사합니다 – cyj

+0

@dmahapatro @dmahapatro 수동으로 도메인의 초기화 서비스는 단위 테스트를 할 때 편리하지 않습니다. 왜냐하면 각 도메인은 여러 서비스를 사용할 수 있기 때문에 각 단위 테스트에서 다중 도메인을 사용할 수 있습니다. 이 문제를 해결 하시겠습니까? – cyj

답변

0

@Mock([User, HiService]) 
 
class HiServiceTest extends Specification { 
 

 
    def "test sayHi"() { 
 
     // .... 
 
    } 
 
}

0

당신이 단위 테스트를 작성하기 때문에이 서비스 autowire가되지 않습니다. 또한 User 클래스 객체를 단위 테스트 할 때 UserSpec에 테스트를 작성해야합니다 (UserServceTest 대신 Suffixing Spec이 Spock의 규칙 임). 이제 다음과 같이 대신 HiService을 조롱 할 수 있습니다`블록 :

클래스 UserSpec는

관련 문제