Weryfikacja aktywnego Nunit

Deti

Do czego to służy?

NUnit jest jednym z testujących narzędzi pod platformę .NET. Za jego pomocą można łatwo i przyjemnie pisać testy jednostkowe kodu (przyszłego lub wcześniej zaprojektowanego).

Gotowiec ten pozwala na weryfikacje, czy aktualny "proces" jest wykonywany z narzędzia NUnit, to znaczy: czy to co aktualnie się uruchamia to rzeczywiste działanie, czy tylko wykonujący się test jednostkowy NUnit.

Jak to działa?

Aby zweryfikować test, należy się posłużyć statyczną właściwością bool IsTestRunning z klasy TestsUtility. Weryfikacja polega na przeczesaniu całego stosu i sprawdzeniu czy jakakolwiek metoda ma atrybut pochodzący z framework'a NUnit, tj. Test, TestFixture, SetUp, TearDown itd itd.

Gotowiec


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Reflection;

using NUnit.Framework;

namespace HAKGERSoft.Common {

    public class TestsUtility {
        static string TestNamespace = "NUnit.Framework";
        static readonly Type[] collected = null;

        static object qd = new object();
        static bool verified = false;

        static TestsUtility() {
            collected = Collect().ToArray();
            if(collected==null)
                throw new ApplicationException("NUnit assembly not installed");
        }

        static bool _IsTestRunning = true;
        public static bool IsTestRunning {
            get {
                lock(qd) {
                    if(!verified) {
                        verified = true;
                        _IsTestRunning = VerifyRunningTest();
                    }
                    return _IsTestRunning;
                }
            }
        }

        static bool VerifyRunningTest() {
            StackTrace trace = new StackTrace();
            for(int i = 0; i < trace.FrameCount; i++) {
                MethodBase methodBase = trace.GetFrame(i).GetMethod();
                if(HasTestAttribute(methodBase))
                    return true;
            }
            return false;
        }

        static bool HasTestAttribute(MethodBase method) {
            foreach(Type type in collected)
                if(method.IsDefined(type, false))
                    return true;
            return false;
        }

        static IEnumerable<Type> Collect() {
            foreach(Type type in Assembly.GetAssembly(typeof(NUnit.Framework.TestAttribute)).GetTypes())
                if(type.Namespace==TestNamespace && AttributeInherit(type))
                    yield return type;
        }

        static bool AttributeInherit(Type type) {
            while(type!=null && (type = type.BaseType)!=null)
                if(type.Equals(typeof(Attribute)))
                    return true;
            return false;
        }



    }
}

0 komentarzy