Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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"

like image 397
raghu Avatar asked Oct 06 '12 07:10

raghu


1 Answers

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()
like image 198
Jay Prall Avatar answered Oct 19 '22 08:10

Jay Prall