2013-08-16 41 views
0

想要測試自定義TagLib的addJsFile方法的「測試新手」總數。我錯過了什麼?測試使用請求對象的自定義Grails TagLib方法

標籤庫:

import com.company.group.application.helper.Util 
... 
class MyTagLib { 
    static namespace = 'mytag' 
    def util 
    ... 
    def addJsFile = { 
     if (util.isSecureRequest(request)) { 
      out << '<script src="https://domain.com/jsfile.js"></script>' 
     } else { 
      out << '<script src="http://domain.com/jsfile.js"></script>' 
     } 
    } 
} 

測試(只要我能得到):

import org.springframework.http.HttpRequest 
import com.company.group.application.helper.Util 

@TestFor(MyTagLib) 
class MyTagLibTests { 
    def util 
    ... 
    void testAddJsFileSecure() { 
     def mockUtil = mockFor(Util) 
     mockUtil.demand.isSecureRequest() { HttpRequest request -> true } 
     def jsCall = applyTemplate('<mytag:addJsFile />') 
     assertEquals('<script src="https://domain.com/jsfile.js"></script>', jsCall) 
    } 
    void testAddJsFileNotSecure() { 
     def mockUtil = mockFor(Util) 
     mockUtil.demand.isSecureRequest() { HttpRequest request -> false } 
     def jsCall = applyTemplate('<mytag:addJsFile/>') 
     assertEquals('<script src="http://domain.com/jsfile.js"></script>', jsCall) 
    } 
} 

的Util isSecureRequest

boolean isSecureRequest(request) { 
    return [true or false] 
} 

錯誤

org.codehaus.groovy.grails.web.taglib.exceptions.GrailsTagException: Error executing tag <mytag:addJsFile>: Cannot invoke method isSecureRequest() on null object 
+0

答案有幫助嗎? – dmahapatro

回答

2

您需要設置tagLib嘲笑util才能使用它。

void testAddJsFileSecure() { 
    def mockUtilControl = mockFor(Util) 
    mockUtilControl.demand.isSecureRequest() { HttpRequest request -> true } 

    //"tagLib" is the default bind object provided 
    //by the mock api when @TestFor is used 
    tagLib.util = mockUtilControl.createMock() 

    //Also note mockFor() returns a mock control 
    //which on createMock() gives the actual mocked object 

    def jsCall = applyTemplate('<mytag:addJsFile />') 
    assertEquals('<script src="https://domain.com/jsfile.js"></script>', jsCall) 

    //In the end of test you can also verify that the mocked object was called 
    mockUtilControl.verify() 
} 

您在測試中不需要def util

相關問題