简体   繁体   中英

Unit testing nested lists

I'm writing unit tests for LINQ repository. I have the following test:

[TestMethod]
public void Find_Method_MustReturn_Customer_Orders_ItemsWithinOrder()
{
      Customer c = _rep.Find(6).SingleOrDefault();
      Assert.IsTrue(c.Orders.Count > 0);                        
}

I can see whether customer has made any orders. Additionally, I'd like to use LINQ to check whether Orders have any items.

How can I achieve this?

Thank you

I think something like this should work:

var items = 
    From o In c.Orders
    From i In o.Items
    Select i;
Assert.IsTrue(items.Any());

This is the equivalent of:

Assert.IsTrue(c.SelectMany(x => x.Items).Any());

This will assert that customer has orders and that each order has items.

[TestMethod]
public void Find_Method_MustReturn_Customer_Orders_ItemsWithinOrder()
{
    Customer c = _rep.Find(6).SingleOrDefault();
    Assert.IsTrue(c.Orders.Any());      
    Assert.IsTrue(c.Orders.Any(x => x.Items.Any());                        
}

Would a foreach suffice?

foreach(var order in c.Orders)
{
    Assert.IsTrue(order.Items.Count > 0);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM