我在谷歌搜索同样的事情时偶然发现了你的问题。如果找到这篇文章,但不喜欢事后必须“解析”生成的 XML 的想法。在筛选了 JAXB Javadoc 之后,我找到了一种我非常喜欢的方法。JAXBMarshaller
提供了一种将 SAXContentHandler
作为参数的方法。您可以模拟它ContentHandler
并验证是否已使用预期参数调用了特定方法。
这是一个小例子。我编写了一个自定义Attributes
匹配器,它只验证某些属性本地名称的存在,但不查看值(还)。我希望这个对你有用:
@Mock
private ContentHandler handler;
private JAXBContext context;
private ObjectFactory factory;
private Marshaller marshaller;
@Before
public void setUp() throws Exception
{
context = JAXBContext.newInstance(getClass().getPackage().getName());
factory = new ObjectFactory();
marshaller = context.createMarshaller();
}
@Test
public void test() throws Exception
{
final UpdateDescription description = new UpdateDescription("identifier", "version");
final JAXBElement<UpdateDescription> element = factory.createUpdateDescription(description);
marshaller.marshal(element, handler);
verify(handler).startDocument();
verify(handler).startElement(anyString(), eq("description"), anyString(), any(Attributes.class));
verify(handler).startElement(anyString(), eq("identifier"), anyString(), attrs("value"));
verify(handler).startElement(anyString(), eq("version"), anyString(), attrs("value"));
verify(handler).endDocument();
}
private static Attributes attrs(final String... localNames)
{
final Matcher<Attributes> matcher = new TypeSafeMatcher<Attributes>()
{
private Set<String> names = Sets.<String> newHashSet(localNames);
@Override
public void describeTo(final Description description)
{
// TODO Auto-generated method stub
}
@Override
public boolean matchesSafely(final Attributes item)
{
final Set<String> presentLocalNames = Sets.newHashSetWithExpectedSize(item.getLength());
final int length = item.getLength();
for (int i = 0; i < length; ++i) {
presentLocalNames.add(item.getLocalName(i));
}
return Sets.difference(names, presentLocalNames).isEmpty();
}
};
return new ThreadSafeMockingProgress().getArgumentMatcherStorage().reportMatcher(matcher).returnFor(
new AttributesImpl());
}