GrailsInAction / graina2

Source code for the 2nd edition of Grails in Action
90 stars 92 forks source link

Chapter 7: refactor example test that uses mocks #26

Open pledbrook opened 11 years ago

pledbrook commented 11 years ago

One of the example test cases in chapter 7 looks like this:

def "Adding new post via mocked service layer honours functionality"() {

    given: "a mock post service"
    def mockPostService = Mock(PostService)    #1
    1 * mockPostService.createPost(_, _) >> new Post(content: "Mock Post") #2
    controller.postService = mockPostService   #3

    when:  "controller is invoked"
    def result = controller.addPost("joe_cool", "Posting up a storm") #4

    then: "redirected to timeline, flash message tells us all is well"
    flash.message ==~ /Added new post: Mock.*/    #5
    response.redirectedUrl == '/post/timeline/joe_cool'   #6

}

As the call to createPost() is a required interaction and should be verified, it makes sense to move it into the 'then:' block like so:

then: "..."
1 * mockPostService.createPost(_, _) >> new Post(content: "Mock Post")
flash.message ==~ /Added new post: Mock.*/
response.redirectedUrl == '/post/timeline/joe_cool'

To be honest, we should also be verifying the content parameter of the createPost() call! So perhaps the interaction line should be:

when:  "controller is invoked"
def postContent = "Posting up a storm"
def result = controller.addPost("joe_cool", postContent) #4

then: "redirected to timeline, flash message tells us all is well"
1 * mockPostService.createPost(_, postContent) >> new Post(content: postContent)
pledbrook commented 11 years ago

This also impacts chapter 9 as I refer back to this example.