Grails spock单元测试用于重定向和渲染

时间:2017-10-23 09:33:27

标签: unit-testing grails spock

我有以下功能进行单元测试。但我仍然坚持如何准确地测试它。还有必要对这些功能进行单元测试吗?我正在使用Grails 2.5.1和spock 0.7。请建议。

    def allGeneralNotes() {
    def ben = Beneficiary.findById(params.id)
    if(!ben){
        redirect(controller: 'dashboard',action: 'index')
    }

    def generalNotes = Note.findAllByBeneficiaryAndTypeAndIsDeleted(Beneficiary.findById(params.id), NoteType.GENERAL,false).sort { it.dateCreated }.reverse()
    def userNames =  noteService.getUserName(generalNotes);
    render view: 'generalNotes', model: [id: params.id, generalNotes: generalNotes, userNames:userNames]
}

1 个答案:

答案 0 :(得分:1)

我不得不承担一些方面的名称,但希望以下内容能让你朝着正确的方向前进。 需要注意的一点是,您在控制器方法中调用了Beneficiary.findById(params.id)两次,您可以将ben传递给findAllByBeneficiaryAndTypeAndIsDeleted

您可能还必须为下面的模拟方法返回的新对象添加参数。

@TestFor( BeneficiaryController )
@Mock( [ Beneficiary, Note ] )
class BeneficiaryControllerSpec extends Specification {

    def noteService = Mock( NoteService )

    void setup() {
        controller.noteService = noteService
    }

    void "test allGeneralNotes no beneficiary" () {
        when:
            controller.allGeneralNotes()
        then:
            response.redirectedUrl == '/dashboard/index'
    }

    void "test allGeneralNotes beneficiary found" () {
        given:
            Beneficiary.metaClass.static.findById{ a -> new Beneficiary()}
            Note.findAllByBeneficiaryAndTypeAndIsDeleted = { a, b -> [new Note(dateCreated: new Date()), new Note(dateCreated: new Date())]}
        when:
            controller.allGeneralNotes()
        then:
            1 * noteService.getUserName( _ ) >> 'whatever username is'
            view == '/generalNotes'
    }
}