2013-03-14 34 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 

    } 
} 
相关问题