How to test XELement and its child elements?
-
28-06-2021 - |
Question
I have a sample Xml code snippet
<modification name="givenName" operation="add" xmlns="urn:oasis:names:tc:DSML:2:0:core">
<value>Changed name</value>
</modification>
The xml is loaded to my XElement, and I used
XElement xml = ...to load xml above...;
xml.Should().HaveAttribute("name", "givenName")
.And.HaveAttribute("operation", "add")
.And.HaveAttribute("xmlns", "urn:oasis:names:tc:DSML:2:0:core")
.And.HaveElement("value");
to test my code, the attributes testing are all passed, but the element testing (the last condition) fails.
Anyone can point out what is wrong with my code?
And how can I test the Xml has an element named "value" and its value is "Changed name"?
Thanks in advance!
Solution
I suspect the problem is that the XName
of the element isn't just value
- it's value
with a namespace. Presumably HaveElement
is namespace-aware. Try this:
XElement xml = ...to load xml above...;
XNamespace ns = "urn:oasis:names:tc:DSML:2:0:core";
xml.Should().HaveAttribute("name", "givenName")
.And.HaveAttribute("operation", "add")
.And.HaveAttribute("xmlns", "urn:oasis:names:tc:DSML:2:0:core")
.And.HaveElement(ns + "value");
The last line checks whether it's got the namespace-qualified element.
OTHER TIPS
It's going to be part of Fluent Assertions 2.1. If you can't wait you can get it through the Git repository
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow