I have a simple object I'm trying to serialize using DataContractSerializer.
In my unit test, I'm trying to verify the xml contains the right value for the product/sku node.
My product class:
[DataContract(Namespace = "http://foo.com/catalogue/")
partial class Product
{
[DataMember(Name = "sku")]
public virtual string ProductSKU
{
get { return _productSKU; }
set
{
OnProductSKUChanging();
_productSKU = value;
OnProductSKUChanged();
}
}
}
Here's the method I'm testing:
public XDocument GetProductXML(Product product)
{
var serializer = new DataContractSerializer(typeof(Product));
var document = new XDocument();
using (var writer = document.CreateWriter())
{
serializer.WriteObject(writer, product);
writer.Close();
}
return document;
}
And here's my unit test:
[Test]
public void Can_get_product_xml()
{
// Arrange
var product = new Product {Id = 1, Name = "Foo Balls", ProductSKU = "Foo123"};
var repository = new CatalogueRepository();
var expectedProductSKU = "Foo123";
// Act
var xml = repository.GetProductXML(product);
var actualProductSKU = xml.Element("product").Element("sku").Value;
// Assert
Assert.AreEqual(expectedProductSKU, actualProductSKU);
}
The problem is that I get a Null reference when I try and access the xml elements, even though when I set a break point the var xml contains:
<product xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://foo.com catalogue/">
<sku>Foo123</sku>
</product>
Any ideas why this is not working? Do I need to parse the serialized stream before adding it to the XDocument?