Basit Bir Mock Framework Geliştirelim 5

2023-05-11

Şu anda, bizim Mock sınıfımızda bir metodun belirli bir sonucu döndürmesini veya bir dizi sonuç döndürmesini ayarlayabiliyoruz. Ancak, belirli bir durumda bir metot çağrıldığında bir hata fırlatmasını isteyebiliriz. Bu, genellikle “Throws” olarak adlandırılır.

using System;
using System.Collections.Concurrent;
using System.Linq.Expressions;
using System.Reflection;
using System.Collections.Generic;

public class Mock<T> : DispatchProxy
{
    private ConcurrentDictionary<string, object> _methodResponses = new();
    private ConcurrentDictionary<string, Queue<object>> _methodSequences = new();
    private ConcurrentDictionary<string, Exception> _methodExceptions = new();
    private ConcurrentDictionary<string, int> _methodCalls = new();

    protected override object Invoke(MethodInfo targetMethod, object[] args)
    {
        var key = GetKey(targetMethod, args);
        var wildcardKey = $"{targetMethod.Name}_*";

        if (_methodExceptions.TryGetValue(key, out var exception))
        {
            _methodCalls[key]++;
            throw exception;
        }
        else if (_methodExceptions.TryGetValue(wildcardKey, out exception))
        {
            _methodCalls[wildcardKey]++;
            throw exception;
        }
        else if (_methodSequences.TryGetValue(key, out var sequence) && sequence.Count > 0)
        {
            _methodCalls[key]++;
            return sequence.Dequeue();
        }
        else if (_methodSequences.TryGetValue(wildcardKey, out sequence) && sequence.Count > 0)
        {
            _methodCalls[wildcardKey]++;
            return sequence.Dequeue();
        }
        else if (_methodResponses.TryGetValue(key, out var value))
        {
            _methodCalls[key]++;
            return value;
        }
        else if (_methodResponses.TryGetValue(wildcardKey, out value))
        {
            _methodCalls[wildcardKey]++;
            return value;
        }

        throw new Exception($"No response set up for method {targetMethod.Name}");
    }

    private string GetKey(MethodInfo methodInfo, object[] args)
    {
        return $"{methodInfo.Name}_{string.Join("_", args)}";
    }

    public void Setup(Expression<Action<T>> expression, object response)
    {
        SetupMethod(expression, response, _methodResponses);
    }

    public void SetupThrows(Expression<Action<T>> expression, Exception exception)
    {
        SetupMethod(expression, exception, _methodExceptions);
    }

    public void SetupSequence(Expression<Action<T>> expression, params object[] responses)
    {
        var queue = new Queue<object>(responses);
        SetupMethod(expression, queue, _methodSequences);
    }

    private void SetupMethod(Expression<Action<T>> expression, object response, ConcurrentDictionary<string, object> dictionary)
    {
        var methodCall = expression.Body as MethodCallExpression;
        var methodName = methodCall.Method.Name;
        var arguments = new object[methodCall.Arguments.Count];
        for (int i = 0; i < methodCall.Arguments.Count; i++)
        {
            var arg = methodCall.Arguments[i];
            if (arg.NodeType == ExpressionType.Constant)
            {
                arguments[i] = ((ConstantExpression)arg).Value;
            }
            else if (arg.NodeType == ExpressionType.Call && ((MethodCallExpression)arg).Method.Name == "IsAny" && ((MethodCallExpression)arg).Object.Type.Name == "It")
            {
                arguments[i] = "*";
            }
        }
        var key = GetKey(methodCall.Method, arguments);
        dictionary.TryAdd(key, response);
    }

    public void Verify(Expression<Action<T>> expression, int expectedInvocationCount = 1)
    {
        var methodCall = expression.Body as MethodCallExpression;
        var methodName = methodCall.Method.Name;
        var arguments = new object[methodCall.Arguments.Count];
        for (int i = 0; i < methodCall.Arguments.Count; i++)
        {
            var arg = methodCall.Arguments[i];
            if (arg.NodeType == ExpressionType.Constant)
            {
                arguments[i] = ((ConstantExpression)arg).Value;
            }
        }
        var key = GetKey(methodCall.Method, arguments);
        if (_methodCalls.TryGetValue(key, out var actualInvocationCount))
        {
            if (actualInvocationCount != expectedInvocationCount)
            {
                throw new Exception($"Method {methodName} was expected to be called {expectedInvocationCount} times but was called {actualInvocationCount} times.");
            }
        }
        else
        {
            throw new Exception($"Method {methodName} was expected to be called {expectedInvocationCount} times but was not called.");
        }
    }

    public static T Create()
    {
        return Create<T, Mock<T>>();
    }
}

public static class It
{
    public static T IsAny<T>()
    {
        return default;
    }
}

Kullanımı

public interface ITestInterface
{
    string TestMethod(int parameter);
}

public class Test
{
    public void TestMethod()
    {
        var mock = Mock<ITestInterface>.Create();
        (mock as Mock<ITestInterface>).SetupThrows(x => x.TestMethod(It.IsAny<int>()), new Exception("Test exception"));

        try
        {
            var result = mock.TestMethod(5);
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message); // Outputs: Test exception
        }

        (mock as Mock<ITestInterface>).Verify(x => x.TestMethod(5)); // Throws no exception
    }
}

Bu örnekte, ITestInterface arayüzünün TestMethod metodunu mockluyoruz. TestMethod çağrıldığında, hangi parametre kullanılırsa kullanılsın bir hata fırlatılır.



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 