查找不同DLL中的单元测试总数

时间:2015-10-13 11:00:55

标签: vb.net

我有一个项目,我们在不同的DLL中有不同类型的单元测试。我想知道整个解决方案中的单元测试总数,以及使用一些VB / C#代码的测试类别,所有者名称等。

实际上,我需要每天准备报告,在那里我需要显示有多少单元测试由谁和哪个类别编写

我不想打开Visual Studio来了解这一点。

这是其中一个单元测试的示例签名:

<TestMethod()> <Owner("OwnerName"), TestCategory("Category22")>
Public Sub TestName()
    ............
    ............
End Sub   

1 个答案:

答案 0 :(得分:0)

由于使用.Net Framework属性记录了测试方法,因此您可以使用反射来获取所需的信息。在VB.net中,您可以按照以下方式执行此操作。

'Imports System.Reflection
'Imports TestLibrary <- wherever the attributes are defined

Dim assy As Assembly = Assembly.LoadFrom(filename)

Dim owner As OwnerAttribute
Dim category As TestCategoryAttribute

For Each t As Type In assy.GetTypes()
    For Each mi As MethodInfo In t.GetMethods(BindingFlags.Public Or BindingFlags.Instance)
        If Not mi.GetCustomAttributes(GetType(TestMethodAttribute)).Count() = 0 Then
            owner = mi.GetCustomAttribute(Of OwnerAttribute)()
            category = mi.GetCustomAttribute(Of TestCategoryAttribute)()

            System.Diagnostics.Debug.Print("{0} : Owner='{1}' Category='{2}'", 
                                           mi.Name, owner.OwnerName, category.CategoryName)

        End If
    Next
Next

您必须添加测试框架DLL作为项目的引用。 filename是已编译程序集的完整路径(EXE,DLL等)。由于空间原因,我没有包含错误检查。

如果您的测试方法不公开,或者它是静态的,您可以通过分别将绑定标志更改为BindingFlags.NonPublicBindingFlags.Static来获取它。 (documentation提供了更多信息。)

请注意,此方法也适用于C#

Assembly assy = Assembly.LoadFrom(filename);

OwnerAttribute owner = null;
TestCategoryAttribute category = null;

foreach(Type t in assy.GetTypes())
{
    foreach (MethodInfo mi in t.GetMethods(BindingFlags.Public | BindingFlags.Instance))
    {
        if (mi.GetCustomAttributes(typeof(TestMethodAttribute)).Count() != 0)
        {
            owner = mi.GetCustomAttribute<OwnerAttribute>();
            category = mi.GetCustomAttribute<TestCategoryAttribute>();

            System.Diagnostics.Debug.Print("{0} : Owner='{1}' Category='{2}'", 
                                           mi.Name, owner.OwnerName, category.CategoryName);
        }
   }
}
相关问题