Question

In my C# unit tests, I often query for a list of rows based on a list of IDs. I then want to ensure that 1) for all the IDs, there was at least one row found that has that ID and 2) for all the returned rows, each row has an ID that is in the list of IDs to find. Here is how I usually ensure 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 the use of Any and All is convenient for such checks, but I wanted to see if anyone thinks this is less readable than it could be, or if there is perhaps a nicer way of doing two-way checks like this. I'm using MSTest in Visual Studio 2008 Team System for unit testing. This perhaps should be community wiki if it's too subjective.

Edit: I'm now using a solution based on Aviad P.'s suggestion, and also 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()
);
Was it helpful?

Solution

You might choose to use the Except operator:

var resultIds = results.Select(x => x[primaryKey]);

Assert.IsTrue(resultIds.Except(ids).Count() == 0,
 "Returned results had unexpected IDs");

Assert.IsTrue(ids.Except(resultIds).Count() == 0,
 "Not all IDs were found in returned results");

OTHER TIPS

IMO, not as readable as it could be. Create and document a method which returns true / false. Then call Assert.IsTrue(methodWithDescriptiveNameWhichReturnsTrueOrfalse(), "reason for failure");

Here is a snippet of code I made to deal with two enumerables, and throwing exception while doing Unit test In MS Test, it might help :

Use

compare two enumerables:

 MyAssert.AreEnumerableSame(expected,actual);

manage exception

MyAssert.Throws<KeyNotFoundException>(() => repository.GetById(1), string.Empty);

Code

public class MyAssert
    {
        public class AssertAnswer
        {
            public bool Success { get; set; }
            public string Message { get; set; }
        }

        public static void Throws<T>(Action action, string expectedMessage) where T : Exception
        {
            AssertAnswer answer = AssertAction<T>(action, expectedMessage);

            Assert.IsTrue(answer.Success);
            Assert.AreEqual(expectedMessage, answer.Message);
        }

        public static void AreEnumerableSame(IEnumerable<object> enumerable1, IEnumerable<object> enumerable2)
        {
            bool isSameEnumerable = true;
            bool isSameObject ;

            if (enumerable1.Count() == enumerable2.Count())
            {
                foreach (object o1 in enumerable1)
                {
                    isSameObject = false;
                    foreach (object o2 in enumerable2)
                    {
                        if (o2.Equals(o1))
                        {
                            isSameObject = true;
                            break;
                        }
                    }
                    if (!isSameObject)
                    {
                        isSameEnumerable = false;
                        break;
                    }
                }
            }
            else
                isSameEnumerable = false;

            Assert.IsTrue(isSameEnumerable);
        }

        public static AssertAnswer AssertAction<T>(Action action, string expectedMessage) where T : Exception
        {
            AssertAnswer answer = new AssertAnswer();

            try
            {
                action.Invoke();

                answer.Success = false;
                answer.Message = string.Format("Exception of type {0} should be thrown.", typeof(T));
            }
            catch (T exc)
            {
                answer.Success = true;
                answer.Message = expectedMessage;
            }
            catch (Exception e)
            {
                answer.Success = false;
                answer.Message = string.Format("A different Exception was thrown {0}.", e.GetType());
            }

            return answer;
        }
    }

NUnit has the CollectionAssert family of assertions which help readability.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top