代码之家  ›  专栏  ›  技术社区  ›  MatteS

Moq与参数属性继承

  •  3
  • MatteS  · 技术社区  · 15 年前

    基本上,行“let a=(ArgumentsAttribute)p.GetCustomAttributes(typeof(ArgumentsAttribute),true).SingleOrDefault()”不返回属性。。运行代码以查看失败的位置。

    我怎样才能通过这个测试?

    [TestFixture]
    public class MyTests {
        [Test]
        public void shouldFindAndCallMethodWithAttributes() {
            var myInterface = new Mock<MyClass>();
            myInterface.Setup(x => x.MyMarkedMethod(1));
            myInterface.Setup(x => x.MyMarkedMethod(5));
            myInterface.Setup(x => x.MyMarkedMethod(9));
    
            var executor = new MarkedMethodExecutor();
            executor.FindAndCallMethodWithAttributes(myInterface.Object);
    
            myInterface.VerifyAll();
        }
    }
    
    public class MarkedMethodExecutor {
        public void FindAndCallMethodWithAttributes(object anObject) {
            var methods = from m in anObject.GetType().GetMethods()
                          where m.GetCustomAttributes(typeof (ExecuteMeAttribute), true).SingleOrDefault() != null
                          select m;
            foreach (var method in methods) {
                var callInfos = from p in method.GetParameters()
                                let a = (ArgumentsAttribute) p.GetCustomAttributes(typeof (ArgumentsAttribute), true).SingleOrDefault()
                                where a != null
                                select new {Parameter = p, Attribute = a};
                // assume its one argument here for simplicity..
                var attribute = callInfos.Single().Attribute;
                foreach (var argument in attribute.Arguments) {
                    method.Invoke(anObject, new[] {argument});
                }
            }
        }
    }
    
    public class MyClass {
        [ExecuteMe]
        public virtual void MyMarkedMethod([Arguments(1, 5, 9)] int arg) {}
    }
    
    [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
    public class ExecuteMeAttribute : Attribute {}
    
    [AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = true)]
    public class ArgumentsAttribute : Attribute {
        public readonly object[] Arguments;
    
        public ArgumentsAttribute(params object[] arguments) {
            Arguments = arguments;
        }
    }
    
    2 回复  |  直到 15 年前
        1
  •  0
  •   Pablo Castilla    15 年前

    我不明白你的问题:你想设置属性吗?

    你可以用这个函数是的(匹配)。或许这有助于: http://api.moq.me/html/5976987C.htm

        2
  •  0
  •   Judah Gabriel Himango    13 年前

    会用 TypeDescriptor.AddAttributes 方法工作?我很想知道:

    var myInterface = new Mock<IRepository>();
    var attribute = new ExecuteMeAttribute();
    someInstanceTypeDescriptor.AddAttributes(myInterface.Object, attribute);