用匿名类型参数模拟方法 [英] mocking a method with an anonymous type argument

查看:86
本文介绍了用匿名类型参数模拟方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

var connector = new Mock<IConector>();

connector
    .Setup(cn => cn.listar("FetchEstandar", new Estandar(), new {Id = 1}))
    .Returns(new List<Estandar>{ new Estandar {Id = 1} });

 var entidad = connector.Object
     .listar("FetchEstandar", new Estandar(), new {Id = 1});

当我在连接器对象上调用listar时,出现了"Expression Cannot Contain an Anonymouse Type"错误.我已经尝试过使用犀牛模拟游戏和起订量.

when I call listar on the connector Object, I get an "Expression Cannot Contain an Anonymouse Type" error. I've tried with rhino mocks and moq.

有什么方法可以模拟此方法?难道我做错了什么?或者,我可以忽略此参数,但不知道如何.我真的只需要测试第一个参数的值,并且ignorearguments可以工作,但是我不知道如果使用它,是否或者如何获得该值

Is there any way I can mock this method? am I doing something wrong? alternatively, I could ignore this parameter but I don't know how. I really just need to test the value of the first parameter and ignorearguments works but I have no idea whether or how I can get this value if I use it

推荐答案

我不知道这是否是匹配匿名对象的唯一方法,但可以使用It.Is<>()和反射来完成

I do not know if this is the only way to match an anonymous object but it can be done using It.Is<>() and reflection

public class Estandar {
    public int Id { get; set; }
}

public interface IConector {
    IEnumerable<Estandar> listar(string name, Estandar estandar, object key);   
}


[TestMethod]
public void CheckAnonymous() {

    var connector = new Mock<IConector>();

    connector.Setup(cn => cn.listar("FetchEstandar",
                                    It.IsAny<Estandar>(),
                                    It.Is<object>(it => MatchKey(it, 1))))
             .Returns(new List<Estandar> { new Estandar { Id = 1 } });

    var entidad = connector.Object.listar("FetchEstandar", new Estandar(), new { Id = 1 });

    Assert.AreEqual(1, entidad.Count());

}

public static bool MatchKey(object key, int soughtId) {
    var ret = false;
    var prop = key.GetType().GetProperty("Id");
    if (prop != null) {
        var id = (int)prop.GetValue(key, null);
        ret = id == soughtId;
    }
    return  ret;
}

这篇关于用匿名类型参数模拟方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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