0

I want to check if a c# project is NUnit or MSTest based. Currently, I read csproj's file and look for a specific string like below.

const string MSTEST_ELEMENT = "<TestProjectType>UnitTest</TestProjectType>";
const string NUNIT_ELEMENT = @"<Reference Include=""nunit.framework"">";

var file = File.ReadAllText("C:\myfile.csproj");

if (file.Contains(NUNIT_ELEMENT))
{
    result = TestProjectType.NUnit;
} 
else if (file.Contains(MSTEST_ELEMENT))
{
    result = TestProjectType.MSTest;
}

It works as I expected but looking for a specific text in a file is ugly for me. Is there a better way to do this?

Anonymous
  • 9,366
  • 22
  • 83
  • 133

2 Answers2

1

Check the solution for dll reference "NUnit.framework.dll" . For NUnit, it is neccesary to provide reference of that dll.

sandip
  • 31
  • 1
1

You could use a reflection-based approach - load the DLL from the test project, get all of the public types in it, and check for [TestClass] attributes to indicate if it's MSTest, etc.

This sample (works but not really tested) gives an example. You could make it better by referencing the test attribute types in whatever runs this code so you could do proper type comparisons instead of strings.

class Program
    {
        static void Main(string[] args)
        {
            var path =  @"Path\To\Your\Test\Dll";
            //load assembly:
            var assembly = Assembly.LoadFile(path);
            //get all public types:
            var types = assembly.GetExportedTypes();
            foreach (var t in types)
            {
                Console.WriteLine(t.Name);
                //check for [TestClass] attribute:
                var attributes = t.GetCustomAttributes();
                foreach (var attr in attributes)
                {
                    var typeName = attr.TypeId.ToString();
                    Console.WriteLine(attr.TypeId);
                    if (typeName== "Microsoft.VisualStudio.TestTools.UnitTesting.TestClassAttribute")
                    {
                        Console.WriteLine("It's MSTest");
                    }
                    else if (typeName == "Nunit.Tests.TestFixture") //not sure if that's the right type id :)
                    {
                        Console.WriteLine("It's NUnit");
                    }
                    else
                    {
                        Console.WriteLine("I Have no idea what it is");
                    }
                }
            }
            Console.ReadLine();

        }
    }
Stephen Byrne
  • 7,400
  • 1
  • 31
  • 51