1

如何使用 Groovy 在 Canoo Webtest 步骤中根据其文档类型 (dtd) 验证网页?

4

1 回答 1

1

其实我知道答案。但是因为我花了一段时间才让它工作,我想我会分享我的解决方案。这是一个 webtest 宏。如果你愿意,你也可以只使用顺序...

<macrodef name="verifySchema" description="Validate the current document against its schema">
<sequential>
    <groovy description="validate schema" >
        import javax.xml.parsers.ParserConfigurationException
        import javax.xml.parsers.SAXParser
        import javax.xml.parsers.SAXParserFactory

        import java.io.InputStreamReader


        import org.xml.sax.ErrorHandler
        import org.xml.sax.InputSource
        import org.xml.sax.SAXException
        import org.xml.sax.SAXParseException
        import org.xml.sax.XMLReader

        class MyHandler implements org.xml.sax.ErrorHandler {
            void warning(SAXParseException e) throws SAXException {
                println 'WARNING: ' + e.getMessage()
            }

            void error(SAXParseException e) throws SAXException {
                println 'ERROR: ' + e.getMessage()
                throw e
            }

            void fatalError(SAXParseException e) throws SAXException {
                println 'FATAL: ' + e.getMessage()
                throw e
            }
        }


            def factory = SAXParserFactory.newInstance()
            factory.setValidating(true)
            factory.setNamespaceAware(true)

            def parser = factory.newSAXParser()
            def reader = parser.getXMLReader()
            reader.setErrorHandler(new MyHandler())
            def response = step.context.currentResponse.webResponse
            reader.parse(new InputSource(new InputStreamReader(response.contentAsStream,"UTF-8")))
    </groovy>
</sequential>

如果您也想在警告测试中失败,请相应地向处理程序添加一个 throw 语句。

于 2010-11-15T14:07:15.713 回答