I have any array of (Pilot) objects with a (Hanger) property, which may be null, which itself has a (List<Plane>) property. For testing purposes, I want to simplify and 'flatten' this to an anonymous object with properties PilotName (string) and Planes (array) but not sure how to handle a null Hanger property or an empty PlanesList.
(Why anonymous objects? Because the objects of the API I'm testing are read only and I want the test to be 'declarative': self contained, simple and readable... but I'm open to other suggestions. Also I'm trying to learn more about LINQ.)
example
class Pilot
{
public string Name;
public Hanger Hanger;
}
class Hanger
{
public string Name;
public List<Plane> PlaneList;
}
class Plane
{
public string Name;
}
[TestFixture]
class General
{
[Test]
public void Test()
{
var pilots = new Pilot[]
{
new Pilot() { Name = "Higgins" },
new Pilot()
{
Name = "Jones", Hanger = new Hanger()
{
Name = "Area 51",
PlaneList = new List<Plane>()
{
new Plane { Name = "B-52" },
new Plane { Name = "F-14" }
}
}
}
};
var actual = pilots.Select(p => new
{
PilotName = p.Name,
Planes = (p.Hanger == null || p.Hanger.PlaneList.Count == 0) ? null : p.Hanger.PlaneList.Select(h => ne
{
PlaneName = h.Name
}).ToArray()
}).ToArray();
var expected = new[] {
new { PilotName = "Higgins", Planes = null },
new
{
PilotName = "Jones",
Planes = new[] {
new { PlaneName = "B-52" },
new { PlaneName = "F-14" }
}
}
};
Assert.That(actual, Is.EqualTo(expected));
}
The immediate problem is that the line expected... Planes = null errors with,
Cannot assign to anonymous type property but admit the underlying problem may be that using
nullinactualis usingnullis not the best approach in the first place.
Any ideas how to either assign the null array in expected or take a different approach than null in actual?
WhereSelectArrayIteratorcreated by thepilots.Wherecall) and an array. You can useToArray()at the end of theWhereclause to force it into an array.Planesbe an empty collection rather thannull, when there aren't any items. It's much easier to deal with; here's some background reading. Secondly, I suspect you're going to have to make the equality check between actual and expected more 'intelligent'; ie, it's going to have to dive into the objects and collections, and use something likeSequenceEqual.nullHangerit's harder... maybe Null Object Pattern for that. For collections, just returnEnumerable.Empty<type>rather thannull.