raghu
raghu

Reputation: 51

How to mock a service in grails TagLib unit test

I have TagLib, Service and TestCase as follows

How to mock a service in a taglib to get expected result from service

TagLib:

   class SampleTagLib {

     static namespace = "sample"
     def baseService

     def writeName = { attrs, body ->
        def result = baseService.findAttributeValue(attrs.something)

        if(result)
           out << body()
     }
 }

Service:

 class BaseService {

     def findAttributeValue(arg1) {

       return false  
     }
}

TagLibUnitTestCase:

import spock.lang.*
import grails.plugin.spock.*
import org.junit.*
import grails.test.mixin.*
import grails.test.mixin.support.*

import grails.test.mixin.Mock

@TestFor(SampleTagLib)
@Mock(BaseService)
class SampleTagLibSpec extends Specification {
      def template

      def setup(){

         tagLib.baseService = Mock(BaseService)
      }


      def 'writeName'(){
        given:
        tagLib.baseService.findAttributeValue(_) >> true
        def template ='<sample:writeName something='value'>output</sample:writeName>'


        when: 'we render the template'
        def output = applyTemplate(template, [sonething:'value')

        then: 'output'
        output =="output"
     }
 }

But it getting Error condition not satisfied. Getting output = " "

Expected output = "output"

Upvotes: 5

Views: 2675

Answers (1)

Jay Prall
Jay Prall

Reputation: 5465

You need to use the grails mockFor to mock out the service.

See Mocking Collaborators

Untested Example:

def strictControl = mockFor(BaseService)
strictControl.demand.findAttributeValue(1..1) { arg1 -> return true }
taglib.baseService = strictControl.createMock()

Upvotes: 5

Related Questions