我有一个采用XML字符串并对其进行解析的方法,返回一个IEnumerable<Invoice>
。以下是所使用类的定义。请注意,Invoice
包含InvoiceItem
:
public class Invoice
{
public const string XmlName = "invoice";
public int id { get; set; }
public string title { get; set; }
public DateTime timestamp { get; set; }
public bool paid { get; set; }
public IList<InvoiceItem> items { get; set; }
public Invoice() { this.items = new List<InvoiceItem>(); }
public decimal getTotal()
{
if (items == null)
return 0;
decimal total = 0;
foreach (InvoiceItem item in this.items)
total += item.amount;
return total;
}
}
public class InvoiceItem
{
public const string XmlName = "item";
public string description { get; set; }
public decimal amount { get; set; }
}
使用NUnit对方法进行单元测试时,paid
的布尔值发生了一些奇怪的事情。请注意,我已经在.NET Fiddle中测试了该方法,它会返回它应该的所有对象。因此,似乎以下测试(部分代码)有问题:
[Test]
public void readXml_Test()
{
// arrange
// xml stuff...
// expected objects
InvoiceItem item1 = new InvoiceItem { description = "item 1 in invoice 1", amount = 50 };
InvoiceItem item2 = new InvoiceItem { description = "item 2 in invoice 1", amount = 50 };
Invoice invoice1 = new Invoice
{
id = 1,
title = "Aug 2020",
timestamp = DateTime.ParseExact("16/08/2020 09:01:29 AM", "dd/MM/yyyy hh:mm:ss tt", System.Globalization.CultureInfo.InvariantCulture),
paid = true,
items = new List<InvoiceItem>() { item1, item2 }
};
InvoiceItem item3 = new InvoiceItem { description = "item in invoice 2", amount = 100 };
Invoice invoice2 = new Invoice
{
id = 2,
title = "Sep 2020",
timestamp = DateTime.ParseExact("16/08/2020 09:01:29 AM", "dd/MM/yyyy hh:mm:ss tt", System.Globalization.CultureInfo.InvariantCulture),
paid = true,
items = new List<InvoiceItem> { item3 }
};
// act
List<Invoice> actual = xml.readXml().ToList(); // readXml() is the method under test.
// assert
Assert.That(actual.Contains(invoice1));
Assert.That(actual.Contains(invoice2));
}
如前所述,我已经在.NET小提琴中对此进行了测试,并且生成的对象都具有正确的属性值。但是,以上测试得出:
Message: Expected: True
But was: False
没有提及任何例外。由于我知道被测方法有效,因此该测试似乎存在问题。我如何解决它以使其通过?