0

我正在尝试在 Grails 控制器中解析 XML - 我可以成功解析 GET 的结果,但是在接收 PUT 时,我无法从请求中获取值。代码如下。

测试:(放置一个假人,以便我可以测试解析和保存)

import grails.test.mixin.*
import grails.test.mixin.domain.DomainClassUnitTestMixin
import org.junit.*
import com.mycompany.stuff.Person

@TestFor(ServiceController)
@TestMixin(DomainClassUnitTestMixin)
class ServiceControllerTests {
    void testCreateWithXML() {
        mockDomain(Person)
        request.method = "PUT"
        def controller = new ServiceController()
        controller.request.contentType = 'text/xml'
        controller.request.content = '''
                <person>
                    <refId>123-abc</refId>
                    <otherThing>some stuff</otherThing>
                </person>
                '''.stripIndent().getBytes() // note we need the bytes (copied from docs)
        def response = controller.create()
        assert Person.count() == 1
        assertEquals "123-abc", Person.get("123-abc").id
    }
}

控制器:在映射到 create 方法后(正确地)接收 put。

class ServiceController {
...
    def create() {
        if (request.format != "xml") {
            render 406 // Only XML expected
            return
        }

        def requestBody = request.XML
        def objectType  = requestBody.name() as String
        log.info "Received ${objectType} - ${requestBody}"
        if (!(objectType.toLowerCase() in ['person','personsubtype']))
        {
                render (status: 400, text: 'Unknown object type received in PUT')
                return
        }

        def person      = new Person(id: requestBody.person.refId.text())
        person.save()

        log.info "Saved ${person}"
        render 200
    }

使用调试器,我可以看到当接收到请求时,变量requestBody作为NodeChild接收,并且name()是正确的。我还可以看到requestBody.person.refId变量的 metaClass 是 of GPathResult... 但是.text()(and .toString()) 总是 return null。第一个log.info打印输出:

2013-07-09 20:04:07,862 [main] INFO  client.ServiceController  - Received person - 123-abcsome stuff

所以我知道内容是偶然的。

任何和所有建议表示赞赏。我已经尝试了一段时间,但我束手无策。

4

1 回答 1

1

refId从 不恰当地访问requestBody。在您的情况下<person>,它本身由requestBody.

requestBody.refId.text()会给你123-abc

控制器实现和测试用例应该这样写:

def create() {
        if (request.format != "xml") {
            render 406 // Only XML expected
            return
        }

        def requestBody = request.XML
        def objectType  = requestBody.name() as String

        //You can see here objectType is person which signifies
        //requestBody is represented as the parent tag <person> 
        log.info "Received ${objectType} - ${requestBody}"
        if (!(objectType.toLowerCase() in ['person','personsubtype'])) {
            render (status: 400, text: 'Unknown object type received in PUT')
            return
        }

        //Since <person> is represented by requestBody, 
        //refId can be fetched directly from requestBody
        def person = new Person(id: requestBody.refId.text())
        person.save()

        log.info "Saved ${person}"
        render 200
    }

可以优化测试类并且可以删除不需要的项目:-

//Test Class can be optimized
import grails.test.mixin.*
import org.junit.*
import com.mycompany.stuff.Person

@TestFor(ServiceController)
//@Mock annotation does the mocking for domain classes
@Mock(Person)
class ServiceControllerTests {
    void testCreateWithXML() {
        //mockDomain(Person) //Not required, taken care by @Mock
        request.method = "PUT"
        //No need to initialize controller 
        //as @TestFor will provide controller.
        //def controller = new ServiceController()
        controller.request.contentType = 'text/xml'
        controller.request.content = '''
                <person>
                    <refId>123-abc</refId>
                    <otherThing>some stuff</otherThing>
                </person>
                '''.stripIndent().getBytes() // note we need the bytes (copied from docs)
        controller.create()

        assert controller.response.contentAsString == 200
        assert Person.count() == 1
        assertEquals "123-abc", Person.get("123-abc").id
    }
}
于 2013-07-10T02:30:36.453 回答