Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save sbilello/dad1aa3acd126aae0564fa8f21febd84 to your computer and use it in GitHub Desktop.

Select an option

Save sbilello/dad1aa3acd126aae0564fa8f21febd84 to your computer and use it in GitHub Desktop.

Revisions

  1. @jeffsheets jeffsheets created this gist Jun 20, 2014.
    53 changes: 53 additions & 0 deletions AccountControllerTest.groovy
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,53 @@
    import groovy.json.JsonSlurper
    import org.springframework.test.web.servlet.MockMvc
    import static org.springframework.test.web.servlet.setup.MockMvcBuilders.*
    import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
    import static org.springframework.http.HttpStatus.*
    import spock.lang.Specification

    /**
    * A Spock Spring MVC Rest unit test that doesn't require a full spring context
    */
    class AccountControllerTest extends Specification {
    def accountController = new AccountController()
    def securityService = Mock(SecurityService)

    //The magic happens here
    MockMvc mockMvc = standaloneSetup(accountController).build()

    def setup() {
    accountController.securityService = securityService
    }

    def "getAccount test hits the URL and parses JSON output"() {
    when: 'rest account url is hit'
    def response = mockMvc.perform(get('/rest/account')).andReturn().response
    def content = new JsonSlurper().parseText(response.contentAsString)

    then: 'securityService correctly returned account in JSON'
    1 * securityService.getCurrentLogin() >> 'spockUser'

    //Testing the HTTP Status code
    response.status == OK.value()

    //Showing how a contains test could work
    response.contentType.contains('application/json')
    response.contentType == 'application/json;charset=UTF-8'

    //Can test the whole content string that is returned
    response.contentAsString == '{"username":"spockUser"}'

    //Or can use the JsonSlurper version to test the JSON as object
    content.username == 'spockUser'
    }

    def "simple getAccount test without spring mvc json framework"() {
    when: 'getAccount is called'
    def result = accountController.getAccount()

    then: 'securityService correctly returns account'
    1 * securityService.getCurrentLogin() >> 'spockUser'

    result.username == 'spockUser'
    }
    }