Say I have the following:
public interface ISession
{
T Get<T>(dynamic filter); }
}
And I have the following code that I want to test:
var user1 = session.Get<User>(new {Name = "test 1"});
var user2 = session.Get<User>(new {Name = "test 2"});
How would I mock this call?
Using Moq, I tired doing this:
var sessionMock = new Mock<ISession>();
sessionMock.Setup(x => x.Get<User>(new {Name = "test 1")).Returns(new User{Id = 1});
sessionMock.Setup(x => x.Get<User>(new {Name = "test 1")).Returns(new User{Id = 2});
And that didn't work. The returned results is null
I also tried to do the following with Rhino Mocks:
var session = MockRepository.GenerateStub<ISession>();
session.Stub(x => x.Get<User>(new {Name = "test 1"})).Return(new User{Id=1});
No luck either. Null again.
So how would I do this?
Thanks,
Moq provided
It.IsAny<T>
for that case*dynamic is any object
You can use the
It.Is<object>
matcher together with reflection. You cannot use dynamic in expression trees soIt.Is<dynamic>
won't work that's why you need reflection to get the your property value by name:Where
GetPropertyValue
is a little helper:First of all, anonymous objects are not really
dynamic
.If you used
dynamic
objects likeyou could mock it like
by implementing custom argument matcher: