如何嘲笑一个方法调用,需要一个动态对象 [英] How to mock a method call that takes a dynamic object

查看:137
本文介绍了如何嘲笑一个方法调用,需要一个动态对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有以下几点:

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});

没有任何运气。空试。

所以,我会怎么做呢?

谢谢,

推荐答案

在解决方案是使用 It.Is<对象> 与反思一起匹配器。你不能使用表达式目录树动态的,所以 It.Is<动态> 将无法正常工作,这就是为什么你需要思考度日名称的属性值:

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

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



其中, GetPropertyValue 是一个小帮手:

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

这篇关于如何嘲笑一个方法调用,需要一个动态对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆