gpt4 book ai didi

unit-testing - Grails 3.3.8单元测试服务

转载 作者:行者123 更新时间:2023-12-02 15:42:54 25 4
gpt4 key购买 nike

我正在尝试测试使用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 ininction或get resource方法,我认为当测试框架使用该服务时,该服务无法访问该路径。

最佳答案

请参阅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'
}
}

希望对您有所帮助。

关于unit-testing - Grails 3.3.8单元测试服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54835096/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com