Permalink
Browse files

single version of request.setGSON so operator form works regardless o…

…f argument type


Fixes #31
  • Loading branch information...
Rob Fletcher
Rob Fletcher committed Apr 13, 2013
1 parent 6e7e768 commit 152c97da03e2953561395030c2394374a7dc4039
@@ -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 {
@@ -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 = {->
@@ -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
@@ -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
@@ -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.