0

I am building a utility to run the unit test cases, where the user will be provided with the option to select the test they want to run. I am using reflection to get the methods. But it is not working

var assembly = Assembly.Load("TestingAssembly");
var classes = assembly.GetTypes().Where(m => m.GetCustomAttributes(typeof(TestClassAttribute), false).Length > 0);
 foreach (var type in classes)
 {
   var methods= type.GetTypes().Where(m1 => m1.GetCustomAttributes(typeof(TestMethodAttribute), false).Length > 0);
 }

The classes object is always empty. If I iterate through the assembly.GetTypes and get the custom attributes it is returning the count. But still, I am not able to match it. In the below code the attributes contains an item with is TestClassAttribute. But when am matching the attribute's type to TestClassAttribute it fails.

foreach (Type type in assembly.GetTypes())
{
  if (type.GetCustomAttributes().Count() > 0)
   {
     var attributes = type.GetCustomAttributes();
       foreach (var item in attributes)
       {
         if (item.GetType() == Microsoft.VisualStudio.TestTools.UnitTesting.TestClassAttribute)
         {
            //Do something
         }
       }
   }
}
DotNetLearner
  • 95
  • 2
  • 13
  • Is there any reason for not using built in test runners? Btw `type.GetTypes()`shouldn't compile. what is the CLR type of the variable `type`? – Sriram Sakthivel Mar 02 '16 at 10:31
  • Want the test to be executed by testing team as well, who don't have access to visual studio. – DotNetLearner Mar 02 '16 at 10:34
  • Turns out that you can use [VS test agent](http://stackoverflow.com/a/7746926/2530848) or simply use nunit; it comes with a test runner. – Sriram Sakthivel Mar 02 '16 at 10:38
  • I've closed your question being duplicate of the above mentioned one. Hope the related question should help. If you disagree with the duplicate, drop a comment here. Thanks – Sriram Sakthivel Mar 02 '16 at 10:39
  • Thanks for the suggestion for the tool. But can you please tell wats wrong with the code and why it is not working – DotNetLearner Mar 02 '16 at 10:52
  • You've missed typeof keyword here `if (item.GetType() == typeof(Microsoft.VisualStudio.TestTools.UnitTesting.TestClassAttribute))`. Also I see several things which could cause compiler error. I believe this isn't the actual code. To be able to help, we need actual code. – Sriram Sakthivel Mar 02 '16 at 10:57
  • I have the typeof in my code. Sorry about the typo. This is almost the same code I have in my utility – DotNetLearner Mar 02 '16 at 11:05
  • I got the problem resolved. The issue was due to TestingAssembly was built with a different version of Microsoft.VisualStudio.TestTools.UnitTesting.dll, than the one referred in my utility. – DotNetLearner Mar 03 '16 at 11:27

0 Answers0