如何检查项目是否是测试项目? (NUnit、MSTest、xUnit)

2023-12-10

我想检查所选项目(我有源代码)是否是以下框架之一的 TestProject:NUnit、MSTest、xUnit。

对于 MSTest 来说很简单。我可以检查 .csproj 和标签。如果我有 {3AC096D0-A1C2-E12C-1390-A8335801FDAB} 则意味着它是测试项目。

问题是NUnit 和xUnit。我可以在 .csproj 中检查此案例的引用。如果我有 nunit.framework 或 xunit,那就很明显了。但我想知道是否可以以不同的方式检查这一点。

您知道识别测试项目的不同方法吗?


方法之一是检查程序集是否包含测试方法。测试方法的属性如下:

  • NUnit: [Test]
  • MSTest: [TestMethod]
  • xUnit.net:[Fact]

迭代程序集并检查程序集是否包含带有测试方法的类。示例代码:

bool IsAssemblyWithTests(Assembly assembly)
{
    var testMethodTypes = new[]
    {
        typeof(Xunit.FactAttribute),
        typeof(NUnit.Framework.TestAttribute),
        typeof(Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute)
    };

    foreach (var type in assembly.GetTypes())
    {
        if (HasAttribute(type, testMethodTypes)) return true;
    }
    return false;
}

bool HasAttribute(Type type, IEnumerable<Type> testMethodTypes)
{
    foreach (Type testMethodType in testMethodTypes)
    {
        if (type.GetMethods().Any(x => x.GetCustomAttributes(testMethodType, true).Any())) return true;
    }

    return false;
}

您还可以添加更多假设:

  • 检查类是否包含 TestFixture 方法,
  • 检查类/测试方法是否是公共的。

EDIT:

如果您需要使用 C# 解析器,这里是一个 NRefactory 代码示例,用于检查 .cs 文件是否包含带测试的类:

string[] testAttributes = new[]
    {
        "TestMethod", "TestMethodAttribute", // MSTest
        "Fact", "FactAttribute", // Xunit
        "Test", "TestAttribute", // NUnit
    };

bool ContainsTests(IEnumerable<TypeDeclaration> typeDeclarations)
{
    foreach (TypeDeclaration typeDeclaration in typeDeclarations)
    {
        foreach (EntityDeclaration method in typeDeclaration.Members.Where(x => x.EntityType == EntityType.Method))
        {
            foreach (AttributeSection attributeSection in method.Attributes)
            {
                foreach (Attribute atrribute in attributeSection.Attributes)
                {
                    var typeStr = atrribute.Type.ToString();
                    if (testAttributes.Contains(typeStr)) return true;
                }
            }
        }
    }

    return false;
}

NRefactory .cs 文件解析示例:

var stream = new StreamReader("Class1.cs").ReadToEnd();
var syntaxTree = new CSharpParser().Parse(stream);
IEnumerable<TypeDeclaration> classes = syntaxTree.DescendantsAndSelf.OfType<TypeDeclaration>();
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何检查项目是否是测试项目? (NUnit、MSTest、xUnit) 的相关文章

随机推荐