cicero81
cicero81
Reputation Top 5%
cicero81
2 Snippets  (294th place)
Published
2 Channels
Created
2 Channels
Following
Sep 25, 2019
Last Visit
Sep 25, 2019
Registered
79 points  (333rd place)
Reputation
Junior Code Generator
Junior Publisher
Junior Topic Creator
Junior Trend Maker
Junior Autobiographer
Serious Autobiographer

Recent Snippets See all snippets by cicero81

public by cicero81 created Sep 25, 2019  46  0  4  0

Find line number and member name via reflection

This method allows to know the line number and the method name of the caller
using System.Reflection;
using System.Runtime.CompilerServices;

public static void Fail(this object testClass, string message = "",
			[CallerLineNumber] int lineNumber = 0,
			[CallerMemberName] string caller = null)
{
	throw new FailTestException(string.Format("{0}.{1} failed at line {2} {3}", 
		testClass.GetType().FullName, caller, lineNumber, message));
}				
;

public by cicero81 created Sep 25, 2019  46  0  3  0

Create your own test suite to run

This set of methods allow to run a test suite without unit test frameworks like XUnit etc. It can be used across all the C# applications, e.g. UWP
    public static async Task<List<TestResult>> RunTests()
		{
			List<TestResult> res = new List<TestResult>();

			// Consider the namespace of the tests:
			IEnumerable<Type> typelist = GetTypesInNamespace(Assembly.GetExecutingAssembly(), "LiquidTextUWP.Tests");
			foreach (Type testClass in typelist)
			{
				// Get all the test methods in the class:
				foreach (MethodInfo method in testClass.GetMethods())
				{
					LTTestAttribute testAttr = method.GetCustomAttributes<LTTestAttribute>().FirstOrDefault();
					if (testAttr == null)
						continue;
					object instance = Activator.CreateInstance(testClass);
					try
					{
						if (testAttr.IsAsync)
							await (Task) method.Invoke(instance, null);
						else
							method.Invoke(instance, null);
						res.Add(new TestResult(true));
					}
					catch (Exception e)
					{
						res.Add(new TestResult(false, string.Format("{0} - {1}", e.Message, e.InnerException?.Message)));
					}
				}
			}

			return res;
		}

		private static IEnumerable<Type> GetTypesInNamespace(Assembly assembly, string nameSpace)
		{
			return assembly.GetTypes().Where(t => (t.Namespace != null) && t.Namespace.StartsWith(nameSpace));
		}
		
		public struct TestResult
	{
		public bool Success { get; set; }
		public string ErrorMsg { get; set; }

		public TestResult(bool success, string msg = "")
		{
			Success = success;
			ErrorMsg = msg;
		}
	}

	[AttributeUsage(AttributeTargets.Method)]
	public class LTTestAttribute : Attribute
	{
		public bool IsAsync { get; set; } = false;
	}
;