Common method for outputting arrays and lists of any type
20-Apr-1414 Leave a comment
In unit tests I might want to output the results of a returned list of any type. Instead of writing a new method for each type, here are some techniques with thanks to:
http://stackoverflow.com/questions/9655262/common-method-for-printing-arrays-and-lists-of-any-types
Using Join
Split is a useful function, here is the reverse Join
int[] actual = new int[] {1,2,3}
string actual = new string[] {“one”, “two”, “three”}
TestContext.WriteLine(string.Join(“, “, actual));
Using Generics
public void PrintCollection<T>(IEnumerable<T> col)
{
foreach (var item in col) TestContext.WriteLine(item);
}
Using ForEach(Action a)
http://msdn.microsoft.com/en-us/library/bwabdf9z(v=vs.110).aspx
[TestMethod()]
publicvoid AListTest()
{
List<string> target = newList<string>();
target.ForEach(PrintCollection2);
}
privatevoid PrintCollection2(string s)
{
TestContext.WriteLine(s);
}