Tuesday, October 31, 2017

mstest with test cases

I am still wondering why there is not better support in mstest for test-cases as it is in nunit like described in http://nunit.org/docs/2.5/testCase.html ... nevertheless I wrote a code snippet which makes life bit easier... I assemble the data to test into the test-name which is not that bad as it might sound, because in some cases e.g.: testing mathematical functions you want to see the input data which is used directly and so you would write it into the name anyway... so we can use the name of the test and reflect over it like:

         public static int[] GetIntArrayFromName()
            StackTrace t = new StackTrace(skipFrames: 1);
            var frames = t.GetFrames();
            string name = frames.First().GetMethod().Name;
            return name.Split('_').Skip(1).Select(x => int.Parse(x)).ToArray();

so if you call this function inside a test-method which is called something like Test_1_2_3 you will get an array like new[]{1,2,3} which might fit quite well.

            [TestMethod] public void Add_1() => AddMethod(GetIntArrayFromName());
            [TestMethod] public void Add_1_2() => AddMethod(GetIntArrayFromName());
            [TestMethod] public void Add_5_4_6_3_1() => AddMethod(GetIntArrayFromName());
            [TestMethod] public void Add_7_5_1_3_4() => AddMethod(GetIntArrayFromName());
the rest is copy / pasting which is easy...

just to mention it, there do is some kind of support using the data source attribute in mstest... see: https://msdn.microsoft.com/en-us/library/microsoft.visualstudio.testtools.unittesting.datasourceattribute.aspx and https://stackoverflow.com/questions/21608462/how-to-run-unit-test-with-multiple-datasource

No comments: