/// <summary> /// Asserts that the XML fragment contains the searched element or attribute, that it has the expected value, and that this element or attribute is unique in the entire fragment. /// </summary> /// <remarks> /// <para> /// If <paramref name="expectedValue"/> is set to <c>null</c>, the assertion behaves like <see cref="Assert.Xml.Exists(string, IXmlPathLoose, XmlOptions, string, object[])"/>. /// </para> /// </remarks> /// <param name="actualXml">The actual XML fragment.</param> /// <param name="searchedPath">The path of the searched element or attribute in the XML fragment.</param> /// <param name="options">Options for the search.</param> /// <param name="expectedValue">The expected value of the searched item (element or attribute).</param> /// <param name="messageFormat">The custom assertion message format, or null if none.</param> /// <param name="messageArgs">The custom assertion message arguments, or null if none.</param> /// <exception cref="AssertionException">Thrown if the verification failed unless the current <see cref="AssertionContext.AssertionFailureBehavior" /> indicates otherwise.</exception> /// <exception cref="ArgumentNullException">Thrown if <paramref name="actualXml"/>, <paramref name="searchedPath"/>, or <paramref name="options"/> is null.</exception> public static void IsUnique(string actualXml, IXmlPathLoose searchedPath, XmlOptions options, string expectedValue, string messageFormat, params object[] messageArgs) { if (actualXml == null) throw new ArgumentNullException("actualXml"); if (searchedPath == null) throw new ArgumentNullException("searchedPath"); if (options == null) throw new ArgumentNullException("options"); AssertionHelper.Verify(() => { NodeFragment actual; try { actual = Parser.Run(actualXml, options.Value); } catch (XmlException exception) { return new AssertionFailureBuilder("Cannot parse the actual XML fragment.") .SetMessage(messageFormat, messageArgs) .AddException(exception) .ToAssertionFailure(); } int count = actual.CountAt(searchedPath, expectedValue, options.Value); if (count == 1) return null; var builder = new AssertionFailureBuilder("Expected the XML fragment to contain only once the searched XML element or attribute, " + (count == 0 ? "but none was found." : "But several were found.")) .SetMessage(messageFormat, messageArgs) .AddLabeledValue("Item searched", searchedPath.ToString()) .AddRawLabeledValue("Number of items found", count); if (expectedValue != null) { builder.AddLabeledValue("Expected value", expectedValue); } return builder.ToAssertionFailure(); }); }