In my unit tests in C #, I often request a list of strings based on a list of identifiers. Then I want to make sure that 1) for all identifiers, at least one found row is found that has this identifier, and 2) for all returned rows, each row has an identifier that is in the list of identifiers for search. Here is how I usually guarantee that:
Assert.IsTrue(ids.All(
id => results.Any(result => result[primaryKey].Equals(id))
), "Not all IDs were found in returned results");
Assert.IsTrue(results.All(
result => ids.Any(id => result[primaryKey].Equals(id))
), "Returned results had unexpected IDs");
I think that the use of Anyand Allconvenient for such checks, but I wanted to see if anyone thinks this is less readable than it could be, or if possible, so. I use MSTest in Visual Studio 2008 Team System for unit testing. Perhaps it should be a wiki community if it is too subjective.
Edit: Now I am using a solution based on the Aviad P. proposal, as well as the fact that the following test passes:
string[] ids1 = { "a", "b", "c" };
string[] ids2 = { "b", "c", "d", "e" };
string[] ids3 = { "c", "a", "b" };
Assert.AreEqual(
1,
ids1.Except(ids2).Count()
);
Assert.AreEqual(
2,
ids2.Except(ids1).Count()
);
Assert.AreEqual(
0,
ids1.Except(ids3).Count()
);
source
share