简体   繁体   English

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

[英]Grails spock unit test for redirect and render

I have a following function to be unit tested.我有以下功能需要进行单元测试。 But I am stuck on how to exactly test it.但我坚持如何准确测试它。 Also is it necessary to unit test these sorts of functions?是否有必要对这些类型的功能进行单元测试? I am using Grails 2.5.1 and spock 0.7.Please suggest.我正在使用 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]
}

I've had to assume the names for a number of facets but hopefully the following will get you going in the right direction.我不得不假设许多方面的名称,但希望以下内容能让您朝着正确的方向前进。 One thing to note is that you call Beneficiary.findById(params.id) twice in your controller method, you could just pass ben into findAllByBeneficiaryAndTypeAndIsDeleted .需要注意的一件事是,您在控制器方法中两次调用Beneficiary.findById(params.id) ,您可以将ben传递给findAllByBeneficiaryAndTypeAndIsDeleted

You may have to add parameters to the new objects returned by the mocked methods below too.您可能还必须向下面的模拟方法返回的新对象添加参数。

@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'
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM