我正在尝试为将 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
}
}
例外:无法在控制器中的 def Artist = new Artist(request.GSON) 处获取空对象上的属性“manyToOne”
任何帮助将不胜感激..