【问题标题】:FakeItEasy faking abstract class with custom attributes with parameters in constructor throws ArgumentExceptionFakeItEasy 在构造函数中使用带有参数的自定义属性伪造抽象类抛出 ArgumentException
【发布时间】:2019-01-04 19:10:49
【问题描述】:

我收到以下异常:

System.ArgumentException: '仅支持常量和一维数组表达式'

在尝试使用带有构造函数参数的附加属性来伪造一些抽象对象时。

var foo = A.Fake<SelfComplementaryCustomizableTupleConsumer>(
            opt => opt.WithAttributes(
                () => new RequiredVariableNameAttribute(requiredVariableName,requiredVariableType)
                )
            );

值得一提的是,如果我调用不带参数的构造函数,一切都很好。对我来说更有趣的是,如果我用常量替换变量也不会出现问题。

完整代码:

string requiredVariableName = "abc";
Type requiredVariableType = typeof(string);


var foo = A.Fake<SelfComplementaryCustomizableTupleConsumer>(
          opt => opt.WithAttributes(
                () => new RequiredVariableNameAttribute(requiredVariableName,requiredVariableType)
                )
         );
var requiredVariables = foo.GetRequiredVariables();

Assert.IsTrue(requiredVariables.TryGetValue(requiredVariableName, out Type tmp));

【问题讨论】:

    标签: c# lambda custom-attributes fakeiteasy


    【解决方案1】:

    这是由于how the attribute creation expression is analyzed。它不支持所有可能的表达式,因为它会非常复杂。我想可以处理局部变量的情况,但是代码在 Castle.Core 中(FakeItEasy 使用它),所以不要指望很快就会修复。同时,如果可以的话,在表达式中使用常量;如果没有,另一种方法是手动构建表达式(使用Expression.Lambda&lt;Func&lt;Attribute&gt;&gt;(...))。

    编辑:我在 Castle.Core 存储库中打开了 issue

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-21
      • 2021-12-17
      • 1970-01-01
      • 2020-04-12
      相关资源
      最近更新 更多