Basit Bir Test Framework Geliştirelim 10

2023-05-11

Genellikle bir test framework’ünde “Parameterized Tests” veya “Data-Driven Tests” adı verilen bir özellik kullanılır. Bu özellik, bir test metodunun farklı veri setleriyle birden çok kez çalıştırılmasını sağlar. Bizde bu özelliği ekleyelim.

Aşağıda, TestCase adında bir attribute ve TestRunner‘da bu attribute’u işleyecek kodu tanımlayalım, bu sayede TestRunner ıda refactor edelim.

using System;
using System.Reflection;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

// ...

public class TestCaseAttribute : Attribute
{
    public object[] Parameters { get; }

    public TestCaseAttribute(params object[] parameters)
    {
        Parameters = parameters;
    }
}

public static class TestRunner
{
    public static async Task RunTestsAsync<T>()
    {
        var testClassInstance = Activator.CreateInstance<T>();

        var testMethods = typeof(T)
            .GetMethods()
            .Where(m => m.GetCustomAttributes<TestAttribute>().Any())
            .ToList();

        foreach (var testMethod in testMethods)
        {
            var testCaseAttributes = testMethod.GetCustomAttributes<TestCaseAttribute>();

            if (!testCaseAttributes.Any())
            {
                await RunTestMethodAsync(testClassInstance, testMethod);
            }
            else
            {
                foreach (var testCase in testCaseAttributes)
                {
                    await RunTestMethodAsync(testClassInstance, testMethod, testCase.Parameters);
                }
            }
        }
    }

    private static async Task RunTestMethodAsync<T>(T testClassInstance, MethodInfo testMethod, object[] parameters = null)
	{
    	try
    	{
        	// Test metodunu çalıştır ve sonucu bekler
        	if (parameters == null)
        	{
            	await (Task)testMethod.Invoke(testClassInstance, null);
        	}
        	else
        	{
            	await (Task)testMethod.Invoke(testClassInstance, parameters);
        	}

        	// Test başarılı oldu
        	Console.ForegroundColor = ConsoleColor.Green;
        	Console.WriteLine($"{testMethod.Name} PASSED");
    	}
    	catch (Exception ex)
    	{
        	// Test bir hata nedeniyle başarısız oldu
        	Console.ForegroundColor = ConsoleColor.Red;
        	Console.WriteLine($"{testMethod.Name} FAILED");

        	// Exception, bir AssertFailedException ise, hata mesajını yazdır
        	if (ex.InnerException is AssertFailedException assertFailedException)
        	{
            	Console.WriteLine(assertFailedException.Message);
        	}
        	else
        	{
            	// Diğer hataları da yazdır
            	Console.WriteLine(ex.InnerException);
        	}
    	}
    	finally
    	{
        	// Konsol rengini normal rengine döndür
        	Console.ResetColor();
    	}
	}
 	

}

Bu kod, TestRunner‘ın test metotlarını bulurken TestCaseAttribute‘ları aramasını ve bulduğu her bir TestCaseAttribute için test metodunu çalıştırmasını sağlar. Her bir TestCaseAttribute‘un parametreleri, test metoduna argüman olarak verilir. Bu sayede, bir test metodunu farklı parametrelerle birden çok kez çalıştırabilirsiniz.



More posts like this

The SemaphoreSlim Class: Multitask-Based Programming in C#

2023-06-11 | #net #semaphoreslim

Overview The SemaphoreSlim class is a structure used in C# to control one or more threads using a specific resource or operation concurrently. SemaphoreSlim limits the number of threads that can access the resource at the same time. The use of SemaphoreSlim is often used to prevent deadlock situations in multi-threaded applications and to ensure that a specific resource is used by only one or more threads at the same time.

Continue reading 


LINQ and Optimistic Concurrency: Methods for Ensuring Data Integrity

2023-06-11 | #linq #net #optimistic-concurrency

When working with databases, it is of great importance to properly manage concurrent operations and ensure data integrity. Concurrency control is used to manage multiple users or processes accessing the same data concurrently. In this article, we will explore how to ensure data integrity using LINQ (Language Integrated Query) with optimistic concurrency. What is Optimistic Concurrency? Optimistic concurrency is a method where resources are not locked when a transaction begins, but changes are checked before the transaction is completed.

Continue reading 


LINQ and Pessimistic Concurrency: Methods for Ensuring Data Integrity

2023-06-11 | #linq #net #pessimistic-concurrency

When working with databases, managing concurrent operations and ensuring data integrity are of great importance. Concurrency control is used to manage multiple users or processes accessing the same data concurrently. In this article, we will explore how to use LINQ (Language Integrated Query) with pessimistic concurrency to maintain data integrity. What is Pessimistic Concurrency? Pessimistic concurrency is based on the principle of locking the relevant data when a transaction begins and maintaining the lock until the transaction is completed.

Continue reading 