How to mock a method call that takes a dynamic object

后端 未结 3 1457
悲哀的现实
悲哀的现实 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:39

    You can use the It.Is matcher together with reflection. You cannot use dynamic in expression trees so It.Is won't work that's why you need reflection to get the your property value by name:

    sessionMock
        .Setup(x => x.Get(
            It.Is(d => d.GetPropertyValue("Name") == "test 1")))
        .Returns(new User{Id = 1});
    sessionMock
        .Setup(x => x.Get(
            It.Is(d => d.GetPropertyValue("Name") == "test 2")))
        .Returns(new User { Id = 2 });
    
    
    

    Where GetPropertyValue is a little helper:

    public static class ReflectionExtensions
    {
        public static T GetPropertyValue(this object obj, string propertyName)
        {
            return (T) obj.GetType().GetProperty(propertyName).GetValue(obj, null);
        }
    }
    

    提交回复
    热议问题