【发布时间】:2012-11-30 12:34:40
【问题描述】:
我正在尝试为使用 grailsApplication.config 进行一些设置的服务编写单元测试。似乎在我的单元测试中,服务实例无法访问其设置的配置文件(空指针),而当我运行“run-app”时它可以访问该设置。如何在单元测试中配置服务以访问 grailsApplication 服务。
class MapCloudMediaServerControllerTests {
def grailsApplication
@Before
public void setUp(){
grailsApplication.config=
'''
video{
location="C:\\tmp\\" // or shared filesystem drive for a cluster
yamdi{
path="C:\\FFmpeg\\ffmpeg-20121125-git-26c531c-win64-static\\bin\\yamdi"
}
ffmpeg {
fileExtension = "flv" // use flv or mp4
conversionArgs = "-b 600k -r 24 -ar 22050 -ab 96k"
path="C:\\FFmpeg\\ffmpeg-20121125-git-26c531c-win64-static\\bin\\ffmpeg"
makethumb = "-an -ss 00:00:03 -an -r 2 -vframes 1 -y -f mjpeg"
}
ffprobe {
path="C:\\FFmpeg\\ffmpeg-20121125-git-26c531c-win64-static\\bin\\ffprobe"
params=""
}
flowplayer {
version = "3.1.2"
}
swfobject {
version = ""
qtfaststart {
path= "C:\\FFmpeg\\ffmpeg-20121125-git-26c531c-win64-static\\bin\\qtfaststart"
}
} '''
}
@Test
void testMpegtoFlvConvertor() {
log.info "In test Mpg to Flv Convertor function!"
def controller=new MapCloudMediaServerController()
assert controller!=null
controller.videoService=new VideoService()
assert controller.videoService!=null
log.info "Is the video service null? ${controller.videoService==null}"
controller.videoService.grailsApplication=grailsApplication
log.info "Is grailsApplication null? ${controller.videoService.grailsApplication==null}"
//Very important part for simulating the HTTP request
controller.metaClass.request = new MockMultipartHttpServletRequest()
controller.request.contentType="video/mpg"
controller.request.content= new File("..\\MapCloudMediaServer\\web-app\\videoclips\\sample3.mpg").getBytes()
controller.mpegtoFlvConvertor()
byte[] videoOut=IOUtils.toByteArray(controller.response.getOutputStream())
def outputFile=new File("..\\MapCloudMediaServer\\web-app\\videoclips\\testsample3.flv")
outputFile.append(videoOut)
}
}
【问题讨论】:
-
您在此测试中有 TestFor 或任何注释吗?不要重新声明 grailsApplication,mock 自带注解。见
GrailsUnitTestMixin。 -
yes 它有 @TestFor 注释。我删除了“def grailsApplication”,但在 grailsApplication 对象上得到了 null 消息。顺便说一句,我正在使用 Grail 2.1。
-
你能发布堆栈跟踪吗?另外,我不确定你是否可以这样声明配置,因为它是 ConfigObject 的一个实例。我会做一个测试,看看你是否需要使用 ConfigSlurper。
-
我认为它无法解析配置数据。这是错误消息:Cannot cast object 'video{ ...... } }' with class 'java.lang.String' to class 'groovy.util.ConfigObject'
-
看我的编辑,在这种情况下你需要使用 ConfigSlurper。
标签: unit-testing grails config