Grails单元测试控制器GSON

时间:2013-10-15 22:47:01

标签: grails gson

我正在尝试为一个简单的控制器编写单元测试,该控制器将GSON作为输入并写入DB。 GSON因为,输入有嵌套对象。

如果我使用JSON,则单元测试有效,但JSON对嵌套对象有其局限性。

域类:

class Artist { 
    String guid 
    String name 

    static constraints = { 
        name nullable: true 
    }

    static mapping = { 
        guid blank:false, unique: true 
    }

    static hasMany = [albums: Albums] 
    /*static marshalling={ deep 'albums' }*/ 
}

控制器实施:

def create() {
    def artist = new Artist(request.GSON)
    if (!artist.save(flush: true)) {
        artist.errors.each {
        log.error("Error while creating Artist " + it)
        }
        render status: 500, layout: null
        return
    }
    response.status = 201
    render artist as GSON
}

单元测试:

@TestMixin(GsonUnitTestMixin)
@TestFor(ArtistController)
@Mock(Artist)
class ArtistControllerTests {
    void testCreate() {
        request.GSON = "{guid:123,"+
                                       "name: 'Akon',"+
                "albums: ["+
                "{guid:1,"+
                "name:'album 1'"+
                "}]}"
        controller.create()
        assert response.status == 201
       }
   }

例外: 无法在null对象上获取属性'manyToOne' def artist =控制器中的新艺术家(request.GSON)

任何帮助将不胜感激..

0 个答案:

没有答案