我正在尝试测试使用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'
}
}
希望对您有所帮助。