如何在C#中设置带有反射的私有惰性<T>以进行测试?

Ron*_*ijm 11 c# reflection lazy-evaluation

问题描述

我们有一个非常大的系统,过去常常用私人设置器将数据加载到属性中.对于使用测试特定方案,我曾经使用私有setter在这些属性中写入数据.

但是,由于系统变慢,并且正在加载无关紧要的东西,我们使用Lazy类将某些内容更改为延迟加载.但是,现在我不再能够将数据写入这些属性,因此很多单元测试将不再运行.

我们曾经拥有的

要测试的对象:

public class ComplexClass
{
    public DateTime Date { get; private set; }

    public ComplexClass()
    {
        // Sample data, eager loading data into variable
        Date = DateTime.Now;
    }
    public string GetDay()
    {
        if (Date.Day == 1 && Date.Month == 1)
        {
            return "New year!";
        }
        return string.Empty;
    }
}
Run Code Online (Sandbox Code Playgroud)

测试结果如何:

[Test]
public void TestNewyear()
{
    var complexClass = new ComplexClass();
    var newYear = new DateTime(2014, 1, 1);
    ReflectionHelper.SetProperty(complexClass, "Date", newYear);

    Assert.AreEqual("New year!", complexClass.GetDay());
}
Run Code Online (Sandbox Code Playgroud)

上面示例中使用的ReflectionHelper的实现.

public static class ReflectionHelper
{
    public static void SetProperty(object instance, string properyName, object value)
    {
        var type = instance.GetType();

        var propertyInfo = type.GetProperty(properyName);
        propertyInfo.SetValue(instance, Convert.ChangeType(value, propertyInfo.PropertyType), null);
    }
}
Run Code Online (Sandbox Code Playgroud)

我们现在拥有什么

要测试的对象:

public class ComplexClass
{
    private readonly Lazy<DateTime> _date;

    public DateTime Date
    {
        get
        {
            return _date.Value;
        }
    }

    public ComplexClass()
    {
        // Sample data, lazy loading data into variable
        _date = new Lazy<DateTime>(() => DateTime.Now);
    }
    public string GetDay()
    {
        if (Date.Day == 1 && Date.Month == 1)
        {
            return "New year!";
        }
        return string.Empty;
    }
}
Run Code Online (Sandbox Code Playgroud)

试图解决它

现在请记住,这只是一个样本.在很多不同的地方改变了从急切加载到延迟加载的代码更改.因为我们不想更改所有测试的代码,所以最好的选择似乎是改变中间人:ReflectionHelper

这是目前的状态 ReflectionHelper

顺便说一句,我想提前为这段奇怪的代码道歉

public static class ReflectionHelper
{
    public static void SetProperty(object instance, string properyName, object value)
    {
        var type = instance.GetType();

        try
        {
            var propertyInfo = type.GetProperty(properyName);
            propertyInfo.SetValue(instance, Convert.ChangeType(value, propertyInfo.PropertyType), null);
        }
        catch (ArgumentException e)
        {
            if (e.Message == "Property set method not found.")
            {
                // it does not have a setter. Maybe it has a backing field
                var fieldName = PropertyToField(properyName);
                var field = type.GetField(fieldName, BindingFlags.NonPublic | BindingFlags.Instance);

                // Create a new lazy at runtime, of the type value.GetType(), for comparing reasons
                var lazyGeneric = typeof(Lazy<>);
                var lazyGenericOfType = lazyGeneric.MakeGenericType(value.GetType());

                // If the field is indeed a lazy, we can attempt to set the lazy
                if (field.FieldType == lazyGenericOfType)
                {
                    var lazyInstance = Activator.CreateInstance(lazyGenericOfType);
                    var lazyValuefield = lazyGenericOfType.GetField("m_boxed", BindingFlags.NonPublic | BindingFlags.Instance);
                    lazyValuefield.SetValue(lazyInstance, Convert.ChangeType(value, lazyValuefield.FieldType));

                    field.SetValue(instance, Convert.ChangeType(lazyInstance, lazyValuefield.FieldType));
                }

                field.SetValue(instance, Convert.ChangeType(value, field.FieldType));
            }
        }
    }

    private static string PropertyToField(string propertyName)
    {
        return "_" + Char.ToLowerInvariant(propertyName[0]) + propertyName.Substring(1);
    }
}
Run Code Online (Sandbox Code Playgroud)

我遇到的第一个问题是,我无法在运行时创建一个未知类型的委托,所以我试图通过设置内部值来解决这个问题Lazy<T>.

在设置了懒惰的内部值之后,我可以看到它确实设置了.然而,我遇到的问题是,我发现a的内部字段Lazy<T>不是a <T>,但实际上是a Lazy<T>.Boxed.Lazy<T>.Boxed是一个懒惰的内部类,所以我必须以某种方式实例化...

我意识到也许我正在从错误的方向接近这个问题,因为解决方案变得越来越复杂,我怀疑很多人会理解'ReflectionHelper'的奇怪的元编程.

解决这个问题的最佳方法是什么?我可以解决这个问题ReflectionHelper吗?或者我是否必须通过每个单元测试并修改它们?

得到答案后编辑

我从dasblinkenlight得到了一个答案,使SetProperty变得通用.我改为代码,这是最终结果,以防其他人需要它

解决方案

public static class ReflectionHelper
{
    public static void SetProperty<T>(object instance, string properyName, T value)
    {
        var type = instance.GetType();

        var propertyInfo = type.GetProperty(properyName);
        var accessors = propertyInfo.GetAccessors(true);

        // There is a setter, lets use that
        if (accessors.Any(x => x.Name.StartsWith("set_")))
        {
            propertyInfo.SetValue(instance, Convert.ChangeType(value, propertyInfo.PropertyType), null);
        }
        else
        {
            // Try to find the backing field
            var fieldName = PropertyToField(properyName);
            var fieldInfo = type.GetField(fieldName, BindingFlags.NonPublic | BindingFlags.Instance);

            // Cant find a field
            if (fieldInfo == null)
            {
                throw new ArgumentException("Cannot find anything to set.");
            }

            // Its a normal backing field
            if (fieldInfo.FieldType == typeof(T))
            {
                throw new NotImplementedException();
            } 

            // if its a field of type lazy
            if (fieldInfo.FieldType == typeof(Lazy<T>))
            {
                var lazyValue = new Lazy<T>(() => value);
                fieldInfo.SetValue(instance, lazyValue);
            }
            else
            {
                throw new NotImplementedException();
            }
        }
    }

    private static string PropertyToField(string propertyName)
    {
        return "_" + Char.ToLowerInvariant(propertyName[0]) + propertyName.Substring(1);
    }
}
Run Code Online (Sandbox Code Playgroud)

打破这种变化

将变量设置为null不再有效而不显式赋予它类型.

ReflectionHelper.SetProperty(instance, "parameter", null);
Run Code Online (Sandbox Code Playgroud)

必须成为

ReflectionHelper.SetProperty<object>(instance, "parameter", null);
Run Code Online (Sandbox Code Playgroud)

das*_*ght 4

尝试创建SetProperty一个通用方法:

public static void SetProperty<T>(object instance, string properyName, T value)
Run Code Online (Sandbox Code Playgroud)

这应该可以让您捕获 的类型value。使用Tin place,您可以Lazy<T>使用常规 C# 语法构造对象,而不是通过反射:

...
Lazy<T> lazyValue = new Lazy<T>(() => value);
...
Run Code Online (Sandbox Code Playgroud)

现在您可以lazyValue使用以下命令将其写入属性/字段setValue

这对于许多(如果不是全部)单元测试来说应该足够了。