Skip to content

Commit

Permalink
single version of request.setGSON so operator form works regardless o…
Browse files Browse the repository at this point in the history
…f argument type

Fixes #31
  • Loading branch information
robfletcher committed Apr 13, 2013
1 parent 6e7e768 commit 152c97d
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 6 deletions.
15 changes: 9 additions & 6 deletions src/groovy/grails/plugin/gson/test/GsonUnitTestMixin.groovy
Expand Up @@ -7,6 +7,7 @@ import grails.plugin.gson.api.ArtefactEnhancer
import grails.plugin.gson.spring.GsonBuilderFactory
import grails.plugin.gson.support.proxy.DefaultEntityProxyHandler
import grails.test.mixin.support.GrailsUnitTestMixin
import org.codehaus.groovy.grails.web.converters.Converter
import org.junit.*

class GsonUnitTestMixin extends GrailsUnitTestMixin {
Expand Down Expand Up @@ -49,13 +50,15 @@ class GsonUnitTestMixin extends GrailsUnitTestMixin {

def parser = new JsonParser()

HttpServletRequest.metaClass.setGSON = { JsonElement json ->
HttpServletRequest.metaClass.setGSON = { json ->
if (json instanceof Converter) {
json = json.toString()
}
if (json instanceof CharSequence) {
json = parser.parse(json.toString())
}
delegate.contentType = 'application/json'
delegate.content = new Gson().toJson(json).getBytes('UTF-8')
}

HttpServletRequest.metaClass.setGSON = { CharSequence json ->
delegate.setGSON parser.parse(json.toString())
delegate.content = gsonBuilder.create().toJson(json).getBytes('UTF-8')
}

HttpServletResponse.metaClass.getGSON = {->
Expand Down
@@ -1,5 +1,8 @@
package grails.plugin.gson.test

import com.google.gson.Gson
import grails.converters.JSON
import grails.plugin.gson.converters.GSON
import grails.test.mixin.*
import spock.lang.*
import static javax.servlet.http.HttpServletResponse.SC_CREATED
Expand All @@ -8,6 +11,7 @@ import static javax.servlet.http.HttpServletResponse.SC_CREATED
@TestFor(AlbumController)
@TestMixin(GsonUnitTestMixin)
@Mock([Artist, Album])
@Unroll
class UnitTestSupportSpec extends Specification {

Artist artist
Expand Down Expand Up @@ -49,4 +53,26 @@ class UnitTestSupportSpec extends Specification {
album.artist.name == artist.name
}

@Shared def data = [title: "The Next Day", artist: [name: "David Bowie"]]

void 'can assign #type to request.GSON'() {
when:
request.GSON = body

then:
request.GSON.title.asString == data.title
request.GSON.artist.name.asString == data.artist.name

where:
body << [
new Gson().toJson(data),
data,
new Gson().toJsonTree(data),
data as GSON,
data as JSON
]

type = body.getClass().simpleName
}

}

0 comments on commit 152c97d

Please sign in to comment.