user338195
user338195

Reputation:

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

Upvotes: 0

Views: 625

Answers (3)

mathieu
mathieu

Reputation: 31192

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());                        
}

Upvotes: 2

Peter
Peter

Reputation: 14098

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());

Upvotes: 2

Matt Ellen
Matt Ellen

Reputation: 11592

Would a foreach suffice?

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

Upvotes: 0

Related Questions