How to mock a service in grails TagLib unit test

I have TagLib, Service and TestCase as follows

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

TagLib:

class SampleTagLib { static namespace = "sample" def baseService def writeName = { attrs, body -> def result = baseService.findAttributeValue(attrs.something) if(result) out << body() } } 

Services:

  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 the condition for receiving the error is not fulfilled. Getting output = ""

Expected output = "output"

+4
source share
1 answer

You need to use grails mockFor to retrieve the service.

See Mocking Collaborators

Unconfirmed example:

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

Source: https://habr.com/ru/post/1438136/


All Articles