Spock Save Test

时间:2012-07-10 02:09:42

标签: unit-testing grails spock

我正试图测试这种方法

  def save() {

        def activityArtifactInstance = new ActivityArtifact(params)
        def activityInstance = Activity.get(params.activity.id)

        def uploadedFile = request.getFile('myFile')
        if (!uploadedFile.empty) {
            def userDir = new File(ConfigurationHolder.config.getProperty("userfiles").toString(), "/files")
            userDir.mkdirs()
            uploadedFile.transferTo(new File(userDir, uploadedFile.originalFilename))
            activityArtifactInstance.fileName = uploadedFile.originalFilename
        }

        if (!activityArtifactInstance.save(flush: true)) {
            render(view: "create", model: [activityArtifactInstance: activityArtifactInstance, activityInstance: activityInstance])
            return
        }

        flash.message = message(code: 'default.created.message', args: [message(code: 'activityArtifact.label', default: 'ActivityArtifact'), activityArtifactInstance.id])
        redirect(controller: "activity", action: "show", id: activityInstance.id, params: [phaseId:activityInstance.phase.id])
    }

这是我的测试代码: -

 def 'save action: valid activity artifact'() {

        setup:
        mockDomain(ActivityArtifact)
        mockI18N(ActivityArtifactController)
        controller.params.name = "Activity Artiface"

        when:
        controller.save()

        then:
        redirectArgs.action == "show"
        controller.flash.message != null


    }

我得到了这个错误: -

java.lang.NullPointerException:无法在null对象上获取属性“id”

如何调用活动对象的ID

1 个答案:

答案 0 :(得分:1)

您的控制器操作假设有一个activity.id参数,而您的测试没有设置。