How to mock a method call that takes a dynamic object

后端 未结 3 1474
悲哀的现实
悲哀的现实 2021-01-11 15:04

Say I have the following:

public interface ISession 
{
   T Get(dynamic filter); }
}

And I have the following code that I want to

3条回答
  •  长发绾君心
    2021-01-11 15:37

    First of all, anonymous objects are not really dynamic.

    If you used dynamic objects like

    dynamic user1Filter = new ExpandoObject();
    user1Filter.Name = "test 1";
    var user1 = session.Get(user1Filter);
    

    you could mock it like

    sessionMock.Setup(x => x.Get(DynamicFilter.HasName("test 1")));
    

    by implementing custom argument matcher:

    static class DynamicFilter
    {
        [Matcher] public static object HasName(string name) { return null; }
        public static bool HasName(dynamic filter, string name)
        {
            string passedName = filter.Name; //dynamic expression
            return name.Equals(passedName);
        }
    }
    

提交回复
热议问题