2013-03-14 57 views
3

在Grails應用程序中使用UnitSpec for service class運行spock測試用例時,將grailsApplication設置爲null。無法在空對象上獲取屬性「配置」 - Grails服務Spock測試

Error - Cannot get property 'config' on null object 

有人可以告訴我如何配置grailsApplication,而spock測試服務類。

我google了很多,但沒有解決我的問題。

這是代碼。

def accountServiceMock = Mock(AccountService) 
    def accountClientService = new AccountClientService() 
def setup(){ 

    accountClientService.accountWS = accountServiceMock 
    accountClientService.basicAuthInterceptor = authenticatorServiceMock   
} 

def "test account by status() "(){ 
    setup: 
    def mockAccountStatus = "ACTIVE" 
    mockDomain(Account, [accountInstance]) 
    accountClientService.grailsApplication = grailsApplication 

    when: 
    accountClientService.getAccountByStatus(mockAccountStatus) //calling web service by fetching url from default.properties file which is context 

    then: 
    Account.count() != 0 

    where: 
    accountInstance = new Account(10L, "ACTIVE","1234", "firstName", "LastName") 
} 

在帳戶服務類getAccountByStatus()方法調用與web服務的url = grailsApplication.config.ACCOUNTWEBSERVICEURL這是有default.properties中的文件 但是當我運行斯波克測試情況下,拋出錯誤,如

無法獲得財產 '配置' 空對象

+0

您可以發佈您的測試代碼,也許有助於看看發生了什麼事情。 – 2013-03-14 13:52:42

+0

哪個Grails版本?哪個Spock版本? – 2013-03-15 06:32:54

+0

你在做單元測試或集成測試嗎?通過它的外觀,你想做一個集成測試。如果這是真的看這裏http://grails.org/doc/2.2.0/guide/single.html#integrationTesting正確實施測試 – Bart 2013-03-15 14:16:36

回答

3

在這裏你去:

import spock.lang.Specification 
import grails.test.mixin.* 

@TestFor(SomeService) 
class SomeServiceIntegrationSpecSpec extends Specification { 

    def "give me the config value"() { 
     given: config.value = '123' 
     expect: service.valueFromConfig == '123' 
    } 
} 

...和公正參考,SomeService類:

class SomeService { 

    def grailsApplication // autowired 

    def getValueFromConfig() { 
     grailsApplication.config.value 
    } 
} 

上面的例子是愚蠢的簡單,儘管足以顯示它應該如何完成。自動裝配grailsApplication的工作得益於@TestFor註解。如果這個不適合你區分的詳細信息將是必要的:

  • Grails的版本
  • 斯波克版本(插件版本會做的Grails)
  • 從NPE在那裏被拋出?測試服務本身,或者是模擬
  • 是Grails的單元或集成測試
  • 全面測試來源將是hepful

沒有母校什麼確切的是你的情況,你可以永遠只是嘲笑像answered here by j4y的配置(當前時間的最後一個答案)

如果您是單元測試,請記住Config.groovy不是唾沫。另一件值得一提的事情是,如果NPE是從Mock()或'new'關鍵字創建的對象拋出的,那麼沒有什麼自動裝配就不足爲奇了。

+0

我遇到了同樣的問題與Grails 2.3.8 Spock內置。 – 2014-06-16 09:31:21

+0

文檔也說使用doWithConfig,但似乎並沒有工作要麼 – 2014-06-16 09:31:59

+0

我還沒有使用Grails一段時間,所以不知道如何2.3。8解決了這個問題。 你做單元或集成測試嗎? – topr 2014-06-16 09:34:38

1

我有類似的問題。實際上有一個引用grailsApplication的域對象。

從測試分配grailsApplication域修正:

@TestMixin(GrailsUnitTestMixin) 
@TestFor(MyService) 
@Mock([MyDomain]) 
class MyServiceSpec extends Specification { 

    myTest() { 

     grailsApplication.config.myValue = "XXX" 

     def myDomain = MyDomain() 

     myDomain.grailsApplication = grailsApplication 

    } 
} 
相關問題