方法之一是检查程序集是否包含测试方法。测试方法的属性如下:
- 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>();