Gambo
Gambo

Reputation: 1572

Test RESTful JSON Grails Webservice

I want to test my secured webservice to the following:

Can somebody give me some hints how to do this? I have no clue how accessing the grails security service and as well running tests against my controllers when logged in and when not. As well I need some Mock Server or something to test against my controllers or?

Sorry I am very new to this topic but I want to go in the right direction before loosing control over my webservices.

Thank you for your help!

Upvotes: 6

Views: 3223

Answers (2)

barrymac
barrymac

Reputation: 2760

I have similar code which uses the built in (groovy 1.8) JsonSlurper which I think might be more reliable and only needs the functional test plugin but not the REST Client plugin.

    String baseUrlString = 'http://localhost:8080/**YOURAPP**'

    baseURL = baseUrlString

    post('/j_spring_security_check?')

    assertStatus 200
    assertContentDoesNotContain('Access Denied')

    get("/*your test URL*/")

    def jsonObj = new JsonSlurper().parseText(this.response.contentAsString)
    assertEquals(jsonObj.your.object.model, **yourContent**)

Upvotes: 0

Gregg
Gregg

Reputation: 35864

We use the REST Client plugin along with the functional testing plugin to test all our web services.

For example...

void testCreateTag() {
    def name = 'Test Name'
    def jsonText = """
         {
           "class":"Tag",
           "name":"${name}"
         }
      """

    post('/api/tag') {
      headers['x-user-external-id'] = securityUser.externalId
      headers['x-user-api-key'] = securityUser.apiKey
      headers['Content-type'] = 'application/json'
      body {
        jsonText
      }
    }

    def model = this.response.contentAsString
    def map = JSON.parse(model)

    assertNotNull(map.attributes.id)

    Tag.withNewSession {
      def tag = Tag.get(map.attributes.id)

      assertNotNull(tag)
      assertEquals(name, tag.name)
    }
}

Upvotes: 7

Related Questions