如果你测试一个action请求处理对象需要类似REST web应用的请求参数,你可以使用Spring MockHttpServletRequest对象实现。
例如,考虑如下这个action,它执行一个进来请求的数据邦定:def create = {
[book: new Book(params['book']) ]
}
假如你想把book参数模拟成一个XML请求对象,你可以按如下方法做:[code]void testCreateWithXML() {
def controller = new BookController()
controller.request.contentType = ‘text/xml’
controller.request.contents = ‘’'<?xml version="1.0" encoding="ISO-8859-1"?>
The Stand
…
'''.getBytes() // note we need the bytes
def model = controller.create()
assert model.book
assertEquals "The Stand", model.book.title
}[/code]同样你可以通过JSON对象达到这个目的:[code]void testCreateWithJSON() {
def controller = new BookController()
controller.request.contentType = "text/json"
controller.request.content = '{"id":1,"class":"Book","title":"The Stand"}'.getBytes()
def model = controller.create()
assert model.book
assertEquals "The Stand", model.book.title
}[/code]使用JSON,也不要忘记对class属性指定名字,绑定的目标类型。
在XML里,在book节点内这些设置隐含的,但是使用JSON你需要这个属性作为JSON包的一部分。