2017-10-23 17 views
1

다음과 같은 유닛 테스트 기능이 있습니다. 하지만 정확히 테스트하는 방법에 붙어 있습니다. 또한 이러한 종류의 함수를 단위 테스트 할 필요가 있습니까? 나는 Grails 2.5.1과 spock 0.7을 사용하고있다. 제안해라.리다이렉트 및 렌더링을위한 Grails spock 유닛 테스트

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

이이 시험에 관련되지 않은,하지만 당신은'컨트롤을 호출 한 후 render''에 대한 호출을 통해 흘러 갈되도록 redirect'를 호출 한 후 반환하지 않기 때문에 컨트롤러의 동작이 문제가 될 것입니다 '리디렉션 '. 'redirect' 다음에'return'하거나'if {...} '로직을 재구성해야합니다. 그래서'redirect' 아래의 모든 것은'else' 블록에 있습니다. –

답변

1

나는 여러면의 이름을 추측해야했지만 잘하면 다음과 같이하면 올바른 방향으로 갈 수 있습니다. 컨트롤러 메서드에서 Beneficiary.findById(params.id)을 두 번 호출하면 benfindAllByBeneficiaryAndTypeAndIsDeleted에 전달할 수 있습니다.

아래 조롱 된 메서드에서 반환 한 새 개체에 매개 변수를 추가해야 할 수도 있습니다.

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

당신의 노력에 감사드립니다. 그것은 제가 찾고있는 것을 정확하게 분류하는 데 도움이되었습니다. :) – BenHuman

관련 문제