【问题标题】:Grails 3.3.8 unit testing serviceGrails 3.3.8 单元测试服务
【发布时间】:2019-02-22 20:59:29
【问题描述】:

我正在尝试测试使用 src/main/webapp/folder 下的文件的服务方法,但是它不起作用,由于任何原因它似乎没有访问权限或其他什么,获取文件的代码是以下:

def file = grailsApplication.parentContext.getResource("folder/file.txt").file

错误是:

ServletContext resource [/folder/file.txt] cannot be resolved to absolute file path - web application archive not expanded?

有什么想法吗? 这不是 grailsApplication 注入或获取资源方法,我认为该服务在被测试框架使用时无权访问该路径。

【问题讨论】:

  • 如果您操作 grails 应用程序对象并需要访问应用程序资源,您确定您的测试是“单元测试”吗?您可以发布您正在测试的代码和测试本身吗?

标签: unit-testing grails


【解决方案1】:

https://github.com/jeffbrown/davidpadillaservice查看项目。

https://github.com/jeffbrown/davidpadillaservice/blob/master/src/main/resources/folder/file.txt

line number one
line number two
line number three

https://github.com/jeffbrown/davidpadillaservice/blob/master/grails-app/services/davidpadillaservice/SomeResourceService.groovy

package davidpadillaservice

import org.springframework.beans.factory.annotation.Value
import org.springframework.core.io.Resource

class SomeResourceService {

    @Value("classpath:folder/file.txt")
    Resource fileResource

    String getFirstLine() {
        getLine(0)
    }

    String getSecondLine() {
        getLine(1)
    }

    protected String getLine(int index) {
        fileResource.file.readLines().get(index)
    }
}

https://github.com/jeffbrown/davidpadillaservice/blob/master/src/test/groovy/davidpadillaservice/SomeResourceServiceSpec.groovy

package davidpadillaservice

import grails.testing.services.ServiceUnitTest
import spock.lang.Specification

class SomeResourceServiceSpec extends Specification implements ServiceUnitTest<SomeResourceService>{

    void "test interacting with the service"() {
        expect:
        service.firstLine == 'line number one'
        service.secondLine == 'line number two'
    }
}

希望对你有帮助。

【讨论】:

  • 请注意,这种方法会将文件移动到src/main/resources/,并且无需直接与grailsApplication 交互来加载资源。
  • 谢谢,我不得不稍微修改一下我的代码,在将它移到 main/resources 之后,我在 main/webapp 下拥有一切。
  • 它可以与main/webapp/(或您可能喜欢的任何其他目录)一起使用,但如果您使用main/resources,它会是Just Work™。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-31
  • 2016-11-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多