[英]Grails spock unit test for redirect and render
我有以下功能需要进行单元测试。 但我坚持如何准确测试它。 是否有必要对这些类型的功能进行单元测试? 我正在使用 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]
}
我不得不假设许多方面的名称,但希望以下内容能让您朝着正确的方向前进。 需要注意的一件事是,您在控制器方法中两次调用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'
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.