Home > Software design >  How to read controller list, methods and custom attributes by Xunit test
How to read controller list, methods and custom attributes by Xunit test

Time:08-30

I have huge backend project with a lot of controllers and each controller methods. I want to mark each method with custom attribute, something like this

<ApiController>
<Route("[controller]/[action]")>
Public Class OneController
    Inherits ControllerBase

    <MyCustomAttr(State:="OK")>
    <HttpGet>
    Public Function Method1
    ...

    <MyCustomAttr(State:="Has bug")>
    <HttpGet>
    Public Function Method2
    ...

    <MyCustomAttr(State:="Not tested")>
    <HttpGet>
    Public Function Method3
    ...

This project supported with related Xunit project. And I want to realize something report like this

    OneController
        Method1 : OK
        Method2 : Has bug
        Method3 : Not tested
    TwoController
        Method1 : Not implement
        Method2 : Don't working

How I can realize this future?

CodePudding user response:

This is simple solution, created for 5 minutes.

<AttributeUsage(AttributeTargets.Method)>
Public Class StateAttribute
    Inherits Attribute
    Public ReadOnly Value
    Public Sub New(value As String)
        Me.Value = value
    End Sub
End Class

Than Methods marks by this attribute, and in Xunit project we can see current state.

Imports System.Reflection
Imports Xunit
Imports Xunit.Abstractions
Public Class ProjectState
    Private ReadOnly Log As ITestOutputHelper
    Public Sub New(_Log As ITestOutputHelper)
        Log = _Log
    End Sub
    <Fact>
    Sub GetApiState()
        Dim API As Assembly = Assembly.LoadFile("G:\Projects\BackendAPI.dll")
        Dim Types = API.GetTypes()
        Dim Controllers As List(Of Type) = Types.Where(Function(X) X.Name.Contains("Controller")).ToList
        For i As Integer = 0 To Controllers.Count - 1
            Log.WriteLine($"{i   1}. {Controllers(i).Name.Replace("Controller", "")}")
            Dim Methods As List(Of MethodInfo) = DirectCast(Controllers(i), System.Reflection.TypeInfo).DeclaredMethods.ToList
            For j As Integer = 0 To Methods.Count - 1
                Dim Attributes As List(Of CustomAttributeData) = Methods(j).CustomAttributes.ToList
                For k = 0 To Attributes.Count - 1
                    If Attributes(k).AttributeType.Name = "StateAttribute" Then
                        Log.WriteLine($"        {j   1}. {Methods(j).Name} : {Attributes(k).ToString.Replace("[BackendAPI.StateAttribute(", "").Replace(")]", "")}")
                    End If
                Next
            Next
        Next
    End Sub
End Class

and this is result

Api state

  • Related