2014-11-26 7 views
2

Graock 2.4.4를 사용하여 Spock 유닛 테스트에서 GSP를 렌더링합니다. GSP에는 ​​여러 가지 맞춤형 태그 라이브러리가 있으며 그 중 대다수는 외부 서비스를 호출합니다. 문제는 그 taglib에 스텁 서비스를 삽입 할 수 없다는 것이고, 서비스를 호출하면 항상 null입니다.Spock과 Grails를 사용하여 스터브 공동 작업자를 스텁과 클래스로 삽입

@TestMixin(GroovyPageUnitTestMixin) 
@Mock(FooTagLib) 
class MyGspSpec extends Specification { 
    def setup() { 
     def barStub = Stub(BarService) 
     def tagLibStub = GroovyStub(FooTagLib, global:true) { 

     } 
     tagLibStub.barService = barStub 
    } 
    def 'test method'() { 
     when: String result = render('myView', model:[:]) 
     then: assert result != null 
    } 
} 

태그 라이브러리 :

class FooTagLib { 
    static String namespace = "baz" 
    BarService barService 
    Closure<StreamCharBuffer> foo = { GroovyPageAttibutess attrs -> 
     out << barService.something() 
    } 
} 

_foo.gsp 내용 :

:

<baz:foo/> 

나는 또한이 시도했습니다 여기에 내가 간단한 경우의 작업을 얻으려고 무엇

FooTagLib.metaClass.barService = Stub(BarService) //also tried GroovyStub 

나는 심지어 게터를 썼다. 태그 라이브러리와는 스텁하지만, 그것은 작동 중 하나를하지 않았다 : 설정에서

:

태그 라이브러리에서
def barService = Stub(BarService) 
GroovyStub(FooTagLib, global:true) { 
    getBarService() >> barService 
} 

:

BarService barService 
BarService getBarService() { return barService } 
//.... 
out << getBarService().something() 

마지막으로, 일 유일한합니다 (로 getter)는 다음과 같습니다.

FooTagLib.metaClass.getBarService = { -> return Stub(BarService) } 

하지만이 것은 정말 위험한 것 같습니다. 케이.

taglib에 스텁 된 버전을 어떻게 삽입 할 수 있는지 잘 모르겠습니다. 내 마음 속에서 이들 중 적어도 하나는 작동해야하지만, 분명히 나는 ​​잘못된 것을하고있다.

@TestFor(FooTagLib) 
class FooTagLibSpec extends Specification { 

    def setup() { 
     // tagLib is available by default of above annotation is used 
     tagLib.barService = Mock(BarService) { 
      // Mock the service and stub the response 
      1 * serviceMethod() >> { "Hello World Returns" } 
     } 
    } 

    void "test something"() { 
     expect: 'applying template would result in mocked response' 
     applyTemplate('<baz:foo/>') == "Hello World Returns" 
    } 

    void "test taglib method call"() { 
     expect: 
     tagLib.foo() == "Hello World Returns" 
    } 
} 

class FooTagLib { 
    static defaultEncodeAs = [taglib:'html'] 
    static String namespace = "baz"  
    BarService barService 

    Closure<StreamCharBuffer> foo = { attrs -> 
     out << barService.serviceMethod() 
    } 
} 

class BarService { 
    def serviceMethod() { "Hello World" } 
} 

을 나는 당신이 당신의 테스트에서 찾고 있던 체크 포인트를 충족 할 수 있었다 희망 :

+0

여기 좀보세요 : http://stackoverflow.com/questions/12757855/how-to-mock-a-service-in-grails-taglib-unit-test – topr

+0

@topr 문제는 tagLib 테스트 중입니다. 즉, 사용중인 인스턴스가 있습니다. 이 경우에는 페이지를 렌더링하므로 특정 taglib 인스턴스를 처리하지 않습니다. 페이지에 아무 숫자 나 올 수 있기 때문에 앞으로는 아무 방법도 없을 것입니다. –

+0

테스트에서 render를 호출하면 컨트롤러가 호출 될 수 있습니다. 아마도이 컨트롤러에 대한 @TestFor를 사용해보십시오. – topr

답변

0

이 내가 태그 라이브러리에 대한 단위 사양을 통과 할 방법이다. 당신은 또한 사양을 볼 수 있습니다 모의 BarService 문제없이. 정보가 필요한 경우 소리 치십시오.