【发布时间】:2012-03-22 15:00:06
【问题描述】:
我有一个使用 @ResponseBody 和 @XmlElement 编组 (JAXB) 返回大量 XML 的系统。
使用创建的 Schema 验证生成的 XML 的最佳方法是什么?
我仍然需要遍历元素并测试它们,但是 XML Schema 验证将使第二部分变得非常容易。
【问题讨论】:
标签: spring unit-testing spring-mvc integration-testing
我有一个使用 @ResponseBody 和 @XmlElement 编组 (JAXB) 返回大量 XML 的系统。
使用创建的 Schema 验证生成的 XML 的最佳方法是什么?
我仍然需要遍历元素并测试它们,但是 XML Schema 验证将使第二部分变得非常容易。
【问题讨论】:
标签: spring unit-testing spring-mvc integration-testing
Spring 让这一切变得简单(假设您使用 Jaxb2Marshaller):
<bean id="marshaller" class="org.springframework.oxm.jaxb.Jaxb2Marshaller">
<property name="schema" value="file:/some/path/schema.xsd"/>
</bean>
【讨论】:
@ResponseBody 这是我需要测试的(控制器返回基于组合模型的编组 XML)
<bean id="marshaller" class="test.project.util.ClasspathScanningJaxb2Marshaller"><property name="schema" value="classpath:service.xsd" /><property name="basePackages" value="test.project" /></bean>,而不是添加classesToBeBound,我使用了walgemoed.org/2010/12/jaxb2-spring-ws。但是,一切运行良好,从某种意义上说,即使是无效的 xsd 也不会给出任何错误消息
为 JAXB 编组器和解组器设置 XSD 架构:
SchemaFactory schemaFactory = SchemaFactory.newInstance(W3C_XML_SCHEMA_NS_URI);
InputStream schemaStream = openMySchemaFileStream();
Schema schema = schemaFactory.newSchema(new StreamSource(schemaStream));
marshaller.setSchema(schema);
unmarshaller.setSchema(schema);
通过解组验证 XML 字符串:
Reader reader = new StringReader(xml);
StreamSource source = new StreamSource(reader);
unmarshaller.unmarshal(source, YourJAXBClass.class);
通过编组到 SAX 的 DefaultHandler 来验证 JAXB 对象,它什么都不做:
marshaller.marshal(obj, new DefaultHandler());
【讨论】:
@ResponseBody 中的结果?